SlideShare a Scribd company logo
1 of 44
Download to read offline
Beginner to Builder
                          Week 2
                          Richard Schneeman
                          @schneems




June, 2011
Thursday, June 16, 2011
Rails - Week 2
                          • Ruby
                            • Hashes & default params
                          • Classes
                              • Macros
                              • Methods
                            • Instances
                              • Methods
@Schneems
Thursday, June 16, 2011
Rails - Week 2
                          • Code Generation
                            • Migrations
                            • Scaffolding
                          • Validation
                          • Testing (Rspec AutoTest)


@Schneems
Thursday, June 16, 2011
Ruby - Default Params
             def what_is_foo(foo = "default")
               puts "foo is: #{foo}"
             end

             what_is_foo
             >> "foo is: default"

             what_is_foo("not_default")
             >> "foo is: not_default"



@Schneems
Thursday, June 16, 2011
Ruby
                          • Hashes - (Like a Struct)
                           • Key - Value Ok - Different
                             DataTypes
                                          Pairs

                           hash = {:a => 100, “b” => “hello”}
                            >> hash[:a]
                            => 100
                            >> hash[“b”]
                            => hello
                            >> hash.keys
                            => [“b”, :a]
@Schneems
Thursday, June 16, 2011
Ruby - Default Params
                      • Hashes in method parameters
                       • options (a hash) is optional parameter
                       • has a default value
             def list_hash(options = {:default => "foo"})
               options.each do |key, value|
                 puts "key '#{key}' points to '#{value}'"
               end
             end
             list_hash
             >> "key 'default' points to 'foo'"
@Schneems
Thursday, June 16, 2011
Ruby - Default Params
                def list_hash(options = {:default => "foo"})
                     options.each do |key, value|
                          puts "key '#{key}' points to '#{value}'"
                     end
                end
                list_hash(:override => "bar")
                >> "key 'override' points to 'bar'"
                list_hash(:multiple => "values", :can => "be_passed")
                >> "key 'multiple' points to 'values'"
                >> "key 'can' points to 'be_passed'"



@Schneems
Thursday, June 16, 2011
Hashes in Rails
                    • Used heavily as parameters
                     • options (a hash) is optional parameter




                Rails API:   (ActionView::Helpers::FormHelper) text_area
@Schneems
Thursday, June 16, 2011
Hashes in Rails
                    • Used heavily as parameters
                     • options (a hash) is optional parameter




                Rails API:   (ActionView::Helpers::FormHelper) text_area
@Schneems
Thursday, June 16, 2011
Ruby
                          • Objects don’t have attributes
                           • Only methods
                           • Need getter & setter methods




@Schneems
Thursday, June 16, 2011
Attributes
                          class MyClass
                            def my_attribute=(value)
                                @myAttribute = value
                            end
                            def my_attribute
                                @myAttribute
                            end
                          end
                          >> object = MyClass.new
                          >> object.my_attribute = “foo”
                          >> object.my_attribute
                          => “foo”
@Schneems
Thursday, June 16, 2011
Ruby - attr_accessor
                          class Car
                            attr_accessor :color
                          end

                          >>   my_car = Car.new
                          >>   my_car.color = “hot_pink”
                          >>   my_car.color
                          =>   “hot_pink”



@Schneems
Thursday, June 16, 2011
Attributes
                          class MyClass
                            def my_attribute=(value)
                                @myAttribute = value
                            end
                            def my_attribute
                                @myAttribute
                            end
                          end
                          >> object = MyClass.new
                          >> object.my_attribute = “foo”
                          >> object.my_attribute
                          => “foo”
@Schneems
Thursday, June 16, 2011
Ruby - Self
                          class MyClass
                            puts self
                          end
                          >> MyClass # self is our class

                          class MyClass
                            def my_method
                              puts self
                            end
                          end
                          MyClass.new.my_method
                          >> <MyClass:0x1012715a8> # self is our instance



@Schneems
Thursday, June 16, 2011
Ruby - Class Methods
                          class MyClass
                            def self.my_method_1(value)
                              puts value
                            end
                          end
                          MyClass.my_method_1("foo")
                          >> "foo"




@Schneems
Thursday, June 16, 2011
Ruby - Class Methods
                          class MyClass
                            def self.my_method_1(value)
                               puts value
                            end
                          end
                          my_instance = MyClass.new
                          my_instance.my_method_1("foo")
                          >> NoMethodError: undefined method `my_method_1' for
                          #<MyClass:0x100156cf0>
                              from (irb):108
                              from :0

                               def self: declares class methods
@Schneems
Thursday, June 16, 2011
Ruby - Instance Methods
                          class MyClass
                            def my_method_2(value)
                              puts value
                            end
                          end
                          MyClass.my_method_2("foo")
                          >> NoMethodError: undefined method `my_method_2' for
                          MyClass:Class
                            from (irb):114
                            from :0




@Schneems
Thursday, June 16, 2011
Ruby - Instance Methods
                          class MyClass
                            def my_method_2(value)
                              puts value
                            end
                          end
                          my_instance = MyClass.new
                          my_instance.my_method_2("foo")
                          >> "foo"




@Schneems
Thursday, June 16, 2011
Ruby
                          • Class Methods        class Dog

                           • Have self             def self.find(name)
                                                   ...
                          • Instance Methods       end

                           • Don’t (Have self)     def wag_tail(frequency)
                                                     ...
                                                   end
                                                 end




@Schneems
Thursday, June 16, 2011
Ruby
                          • attr_accessor is a Class method
                             class Dog
                               attr_accessor :fur_color
                             end


                                     Can be defined as:
                             class Dog
                               def self.attr_accessor(value)
                                 #...
                               end
                             end

@Schneems                                    cool !
Thursday, June 16, 2011
Rails - Week 2
                          • Code Generation
                           • Migrations
                           • Scaffolding
                          • Validation
                          • Testing (Rspec AutoTest)


@Schneems
Thursday, June 16, 2011
Scaffolding
                           •   Generate Model, View, and Controller &
                               Migration

                          >> rails generate scaffold
                             Post name:string title:string content:text


                           •   Generates “One Size Fits All” code
                               •   app/models/post.rb
                               •   app/controllers/posts_controller.rb
                               •   app/views/posts/ {index, show, new, create,
                                   destroy}
                           •   Modify to suite needs (convention over
                               configuration)
@Schneems
Thursday, June 16, 2011
Database Backed Models
       • Store and access massive amounts of
         data
       • Table
         • columns (name, type, modifier)
         • rows
                          Table: Users




@Schneems
Thursday, June 16, 2011
Create Schema
                      • Create Schema
                       • Multiple machines



                  Enter...Migrations
@Schneems
Thursday, June 16, 2011
Migrations
                             •   Create your data structure in your Database
                                 •   Set a database’s schema
               migrate/create_post.rb
                          class CreatePost < ActiveRecord::Migration
                            def self.up
                              create_table :post do |t|
                                t.string :name
                                t.string :title
                                t.text     :content
                              end
                              SystemSetting.create :name => "notice",
                                       :label => "Use notice?", :value => 1
                            end
                            def self.down
                              drop_table :posts
                            end
                          end

@Schneems
Thursday, June 16, 2011
Migrations
                            •   Get your data structure into your database

                          >> rake db:migrate



                            •   Runs all “Up” migrations
                          def self.up
                           create_table   :post do |t|
                              t.string    :name
                              t.string    :title
                              t.text      :content
                            end
                          end
@Schneems
Thursday, June 16, 2011
Migrations
                                                       def self.up
                                                        create_table :post do |t|
               •          Creates a Table named post         def self.up
                                                           t.string :name do |t|
               •          Adds Columns
                                                              create_table :post
                                                           t.string :title
                                                                 t.string :name
                                                                 t.string :title
                     •      Name, Title, Content           t.textt.text :content
                                                               end
                                                                           :content

                                                         end end
                     •      created_at & updated_at
                            added automatically        end




@Schneems
Thursday, June 16, 2011
Migrations
                          •   Active Record maps ruby objects to database
                              •   Post.title

                                                Active Record is Rail’s ORM
                                    def self.up
                                     create_table   :post do |t|
                                        t.string    :name
                                        t.string    :title
                                        t.text      :content
                                      end
                                    end

@Schneems
Thursday, June 16, 2011
Migrations
                          •   Active Record maps ruby objects to database
                              •   Post.title

                                                Active Record is Rail’s ORM
                                    def self.up
                                     create_table   :post do |t|
                                        t.string    :name
                                        t.string    :title
                                        t.text      :content
                                      end
                                    end

@Schneems
Thursday, June 16, 2011
Migrations
                          •   Active Record maps ruby objects to database
                              •   Post.title

                                                Active Record is Rail’s ORM
                                    def self.up
                                     create_table   :post do |t|
                                        t.string    :name
                                        t.string    :title
                                        t.text      :content
                                      end
                                    end

@Schneems
Thursday, June 16, 2011
Migrations
                          •   Active Record maps ruby objects to database
                              •   Post.title

                                                Active Record is Rail’s ORM
                                    def self.up
                                     create_table   :post do |t|
                                        t.string    :name
                                        t.string    :title
                                        t.text      :content
                                      end
                                    end

@Schneems
Thursday, June 16, 2011
Migrations
                          •   Active Record maps ruby objects to database
                              •   Post.title

                                                Active Record is Rail’s ORM
                                    def self.up
                                     create_table   :post do |t|
                                        t.string    :name
                                        t.string    :title
                                        t.text      :content
                                      end
                                    end

@Schneems
Thursday, June 16, 2011
Migrations
                          •   Made a mistake? Issue a database Ctrl + Z !

                          >> rake db:rollback



                          •   Runs last “down” migration

                          def self.down
                             drop_table :system_settings
                           end




@Schneems
Thursday, June 16, 2011
Rails - Validations
                             •   Check your parameters before save
                                 •   Provided by ActiveModel
                                     •   Utilized by ActiveRecord
                          class Person < ActiveRecord::Base
                            validates :title, :presence => true
                          end

                          bob = Person.create(:title => nil)
                          >> bob.valid?
                          => false
                          >> bob.save
                          => false

@Schneems
Thursday, June 16, 2011
Rails - Validations
                            Can use ActiveModel without Rails
                          class Person
                            include ActiveModel::Validations
                            attr_accessor :title
                            validates :title, :presence => true
                          end

                          bob = Person.create(:title => nil)
                          >> bob.valid?
                          => false
                          >> bob.save
                          => false

@Schneems
Thursday, June 16, 2011
Rails - Validations
                              •    Use Rail’s built in Validations
                          #   :acceptance => Boolean.
                          #   :confirmation => Boolean.
                          #   :exclusion => { :in => Enumerable }.
                          #   :inclusion => { :in => Enumerable }.
                          #   :format => { :with => Regexp, :on => :create }.
                          #   :length => { :maximum => Fixnum }.
                          #   :numericality => Boolean.
                          #   :presence => Boolean.
                          #   :uniqueness => Boolean.

                          •       Write your Own Validations
  class User < ActiveRecord::Base
    validate :my_custom_validation
    private
      def my_custom_validation
        self.errors.add(:coolness, "bad") unless self.cool == “supercool”
      end
  end

@Schneems
Thursday, June 16, 2011
If & Unless
                          puts “hello” if true
                          >> “hello”
                          puts “hello” if false
                          >> nil

                          puts “hello” unless true
                          >> nil
                          puts “hello” unless false
                          >> “hello”




@Schneems
Thursday, June 16, 2011
blank? & present?
                          puts “hello”.blank?
                          >> false
                          puts “hello”.present?
                          >> true
                          puts false.blank?
                          >> true
                          puts nil.blank?
                          >> true
                          puts [].blank?
                          >> true
                          puts “”.blank?
                          >> true




@Schneems
Thursday, June 16, 2011
Testing
                          • Test your code (or wish you did)
                          • Makes upgrading and refactoring easier
                          • Different Environments
                           • production - live on the web
                           • development - on your local computer
                           • test - local clean environment

@Schneems
Thursday, June 16, 2011
Testing
                  • Unit Tests
                   • Test individual methods against known
                      inputs
                  • Integration Tests
                   • Test Multiple Controllers
                  • Functional Tests
                   • Test full stack M- V-C
@Schneems
Thursday, June 16, 2011
Unit Testing
                  • ActiveSupport::TestCase
                  • Provides assert statements
                   • assert true
                   • assert (variable)
                   • assert_same( obj1, obj2 )
                   • many more

@Schneems
Thursday, June 16, 2011
Unit Testing
                          • Run Unit Tests using:
                          >> rake test:units RAILS_ENV=test




@Schneems
Thursday, June 16, 2011
Unit Testing
                          • Run Tests automatically the
                            background
                           • ZenTest
                             • gem install autotest-standalone
                             • Run: >> autotest


@Schneems
Thursday, June 16, 2011
Questions?



@Schneems
Thursday, June 16, 2011

More Related Content

What's hot

Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
Pavel Tyk
 
DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻
都元ダイスケ Miyamoto
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
Juan Maiz
 

What's hot (12)

jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
Learning How To Use Jquery #3
Learning How To Use Jquery #3Learning How To Use Jquery #3
Learning How To Use Jquery #3
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
 
Rails3 Summer of Code 2010- Week 5
Rails3 Summer of Code 2010- Week 5Rails3 Summer of Code 2010- Week 5
Rails3 Summer of Code 2010- Week 5
 
DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Rails for PHP Developers
Rails for PHP DevelopersRails for PHP Developers
Rails for PHP Developers
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 

Viewers also liked

PEShare.co.uk Shared Resource
PEShare.co.uk Shared ResourcePEShare.co.uk Shared Resource
PEShare.co.uk Shared Resource
peshare.co.uk
 
Skill of Observation
Skill of ObservationSkill of Observation
Skill of Observation
Akshat Tewari
 

Viewers also liked (17)

Bc phase one_session10
Bc phase one_session10Bc phase one_session10
Bc phase one_session10
 
PEShare.co.uk Shared Resource
PEShare.co.uk Shared ResourcePEShare.co.uk Shared Resource
PEShare.co.uk Shared Resource
 
Rails 3 Beginner to Builder 2011 Week 6
Rails 3 Beginner to Builder 2011 Week 6Rails 3 Beginner to Builder 2011 Week 6
Rails 3 Beginner to Builder 2011 Week 6
 
Rails 3 Beginner to Builder 2011 Week 1
Rails 3 Beginner to Builder 2011 Week 1Rails 3 Beginner to Builder 2011 Week 1
Rails 3 Beginner to Builder 2011 Week 1
 
Skill of Observation
Skill of ObservationSkill of Observation
Skill of Observation
 
AJAX?? Não!! Asynchronous Javascript and... JSON!!
AJAX?? Não!! Asynchronous Javascript and... JSON!!AJAX?? Não!! Asynchronous Javascript and... JSON!!
AJAX?? Não!! Asynchronous Javascript and... JSON!!
 
Teaching with limited resources checkpoint
Teaching with limited resources checkpointTeaching with limited resources checkpoint
Teaching with limited resources checkpoint
 
Minicurso JSON & Ajax
Minicurso JSON & AjaxMinicurso JSON & Ajax
Minicurso JSON & Ajax
 
First conditional lesson plan for secondary level students
First conditional lesson plan for secondary level studentsFirst conditional lesson plan for secondary level students
First conditional lesson plan for secondary level students
 
Lesson plan simple past
Lesson plan simple pastLesson plan simple past
Lesson plan simple past
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 
Lesson Plan on Modals
Lesson Plan on ModalsLesson Plan on Modals
Lesson Plan on Modals
 
Sample Lesson Plan on Past Simple Tense
Sample Lesson Plan on Past Simple TenseSample Lesson Plan on Past Simple Tense
Sample Lesson Plan on Past Simple Tense
 
Lesson plan
Lesson planLesson plan
Lesson plan
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Lesson Plans
Lesson PlansLesson Plans
Lesson Plans
 
Mini lesson on past tense simple
Mini lesson on past tense simpleMini lesson on past tense simple
Mini lesson on past tense simple
 

More from Richard Schneeman

Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6
Richard Schneeman
 

More from Richard Schneeman (7)

Scaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLScaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQL
 
Rails 3 Beginner to Builder 2011 Week 8
Rails 3 Beginner to Builder 2011 Week 8Rails 3 Beginner to Builder 2011 Week 8
Rails 3 Beginner to Builder 2011 Week 8
 
Rails 3 Beginner to Builder 2011 Week 5
Rails 3 Beginner to Builder 2011 Week 5Rails 3 Beginner to Builder 2011 Week 5
Rails 3 Beginner to Builder 2011 Week 5
 
Potential Friend Finder
Potential Friend FinderPotential Friend Finder
Potential Friend Finder
 
Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6
 
UT on Rails3 2010- Week 4
UT on Rails3 2010- Week 4 UT on Rails3 2010- Week 4
UT on Rails3 2010- Week 4
 
UT on Rails3 2010- Week 1
UT on Rails3 2010- Week 1UT on Rails3 2010- Week 1
UT on Rails3 2010- Week 1
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 

Rails 3 Beginner to Builder 2011 Week 2

  • 1. Beginner to Builder Week 2 Richard Schneeman @schneems June, 2011 Thursday, June 16, 2011
  • 2. Rails - Week 2 • Ruby • Hashes & default params • Classes • Macros • Methods • Instances • Methods @Schneems Thursday, June 16, 2011
  • 3. Rails - Week 2 • Code Generation • Migrations • Scaffolding • Validation • Testing (Rspec AutoTest) @Schneems Thursday, June 16, 2011
  • 4. Ruby - Default Params def what_is_foo(foo = "default") puts "foo is: #{foo}" end what_is_foo >> "foo is: default" what_is_foo("not_default") >> "foo is: not_default" @Schneems Thursday, June 16, 2011
  • 5. Ruby • Hashes - (Like a Struct) • Key - Value Ok - Different DataTypes Pairs hash = {:a => 100, “b” => “hello”} >> hash[:a] => 100 >> hash[“b”] => hello >> hash.keys => [“b”, :a] @Schneems Thursday, June 16, 2011
  • 6. Ruby - Default Params • Hashes in method parameters • options (a hash) is optional parameter • has a default value def list_hash(options = {:default => "foo"}) options.each do |key, value| puts "key '#{key}' points to '#{value}'" end end list_hash >> "key 'default' points to 'foo'" @Schneems Thursday, June 16, 2011
  • 7. Ruby - Default Params def list_hash(options = {:default => "foo"}) options.each do |key, value| puts "key '#{key}' points to '#{value}'" end end list_hash(:override => "bar") >> "key 'override' points to 'bar'" list_hash(:multiple => "values", :can => "be_passed") >> "key 'multiple' points to 'values'" >> "key 'can' points to 'be_passed'" @Schneems Thursday, June 16, 2011
  • 8. Hashes in Rails • Used heavily as parameters • options (a hash) is optional parameter Rails API: (ActionView::Helpers::FormHelper) text_area @Schneems Thursday, June 16, 2011
  • 9. Hashes in Rails • Used heavily as parameters • options (a hash) is optional parameter Rails API: (ActionView::Helpers::FormHelper) text_area @Schneems Thursday, June 16, 2011
  • 10. Ruby • Objects don’t have attributes • Only methods • Need getter & setter methods @Schneems Thursday, June 16, 2011
  • 11. Attributes class MyClass def my_attribute=(value) @myAttribute = value end def my_attribute @myAttribute end end >> object = MyClass.new >> object.my_attribute = “foo” >> object.my_attribute => “foo” @Schneems Thursday, June 16, 2011
  • 12. Ruby - attr_accessor class Car attr_accessor :color end >> my_car = Car.new >> my_car.color = “hot_pink” >> my_car.color => “hot_pink” @Schneems Thursday, June 16, 2011
  • 13. Attributes class MyClass def my_attribute=(value) @myAttribute = value end def my_attribute @myAttribute end end >> object = MyClass.new >> object.my_attribute = “foo” >> object.my_attribute => “foo” @Schneems Thursday, June 16, 2011
  • 14. Ruby - Self class MyClass puts self end >> MyClass # self is our class class MyClass def my_method puts self end end MyClass.new.my_method >> <MyClass:0x1012715a8> # self is our instance @Schneems Thursday, June 16, 2011
  • 15. Ruby - Class Methods class MyClass def self.my_method_1(value) puts value end end MyClass.my_method_1("foo") >> "foo" @Schneems Thursday, June 16, 2011
  • 16. Ruby - Class Methods class MyClass def self.my_method_1(value) puts value end end my_instance = MyClass.new my_instance.my_method_1("foo") >> NoMethodError: undefined method `my_method_1' for #<MyClass:0x100156cf0> from (irb):108 from :0 def self: declares class methods @Schneems Thursday, June 16, 2011
  • 17. Ruby - Instance Methods class MyClass def my_method_2(value) puts value end end MyClass.my_method_2("foo") >> NoMethodError: undefined method `my_method_2' for MyClass:Class from (irb):114 from :0 @Schneems Thursday, June 16, 2011
  • 18. Ruby - Instance Methods class MyClass def my_method_2(value) puts value end end my_instance = MyClass.new my_instance.my_method_2("foo") >> "foo" @Schneems Thursday, June 16, 2011
  • 19. Ruby • Class Methods class Dog • Have self def self.find(name) ... • Instance Methods end • Don’t (Have self) def wag_tail(frequency) ... end end @Schneems Thursday, June 16, 2011
  • 20. Ruby • attr_accessor is a Class method class Dog attr_accessor :fur_color end Can be defined as: class Dog def self.attr_accessor(value) #... end end @Schneems cool ! Thursday, June 16, 2011
  • 21. Rails - Week 2 • Code Generation • Migrations • Scaffolding • Validation • Testing (Rspec AutoTest) @Schneems Thursday, June 16, 2011
  • 22. Scaffolding • Generate Model, View, and Controller & Migration >> rails generate scaffold Post name:string title:string content:text • Generates “One Size Fits All” code • app/models/post.rb • app/controllers/posts_controller.rb • app/views/posts/ {index, show, new, create, destroy} • Modify to suite needs (convention over configuration) @Schneems Thursday, June 16, 2011
  • 23. Database Backed Models • Store and access massive amounts of data • Table • columns (name, type, modifier) • rows Table: Users @Schneems Thursday, June 16, 2011
  • 24. Create Schema • Create Schema • Multiple machines Enter...Migrations @Schneems Thursday, June 16, 2011
  • 25. Migrations • Create your data structure in your Database • Set a database’s schema migrate/create_post.rb class CreatePost < ActiveRecord::Migration def self.up create_table :post do |t| t.string :name t.string :title t.text :content end SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1 end def self.down drop_table :posts end end @Schneems Thursday, June 16, 2011
  • 26. Migrations • Get your data structure into your database >> rake db:migrate • Runs all “Up” migrations def self.up create_table :post do |t| t.string :name t.string :title t.text :content end end @Schneems Thursday, June 16, 2011
  • 27. Migrations def self.up create_table :post do |t| • Creates a Table named post def self.up t.string :name do |t| • Adds Columns create_table :post t.string :title t.string :name t.string :title • Name, Title, Content t.textt.text :content end :content end end • created_at & updated_at added automatically end @Schneems Thursday, June 16, 2011
  • 28. Migrations • Active Record maps ruby objects to database • Post.title Active Record is Rail’s ORM def self.up create_table :post do |t| t.string :name t.string :title t.text :content end end @Schneems Thursday, June 16, 2011
  • 29. Migrations • Active Record maps ruby objects to database • Post.title Active Record is Rail’s ORM def self.up create_table :post do |t| t.string :name t.string :title t.text :content end end @Schneems Thursday, June 16, 2011
  • 30. Migrations • Active Record maps ruby objects to database • Post.title Active Record is Rail’s ORM def self.up create_table :post do |t| t.string :name t.string :title t.text :content end end @Schneems Thursday, June 16, 2011
  • 31. Migrations • Active Record maps ruby objects to database • Post.title Active Record is Rail’s ORM def self.up create_table :post do |t| t.string :name t.string :title t.text :content end end @Schneems Thursday, June 16, 2011
  • 32. Migrations • Active Record maps ruby objects to database • Post.title Active Record is Rail’s ORM def self.up create_table :post do |t| t.string :name t.string :title t.text :content end end @Schneems Thursday, June 16, 2011
  • 33. Migrations • Made a mistake? Issue a database Ctrl + Z ! >> rake db:rollback • Runs last “down” migration def self.down drop_table :system_settings end @Schneems Thursday, June 16, 2011
  • 34. Rails - Validations • Check your parameters before save • Provided by ActiveModel • Utilized by ActiveRecord class Person < ActiveRecord::Base validates :title, :presence => true end bob = Person.create(:title => nil) >> bob.valid? => false >> bob.save => false @Schneems Thursday, June 16, 2011
  • 35. Rails - Validations Can use ActiveModel without Rails class Person include ActiveModel::Validations attr_accessor :title validates :title, :presence => true end bob = Person.create(:title => nil) >> bob.valid? => false >> bob.save => false @Schneems Thursday, June 16, 2011
  • 36. Rails - Validations • Use Rail’s built in Validations # :acceptance => Boolean. # :confirmation => Boolean. # :exclusion => { :in => Enumerable }. # :inclusion => { :in => Enumerable }. # :format => { :with => Regexp, :on => :create }. # :length => { :maximum => Fixnum }. # :numericality => Boolean. # :presence => Boolean. # :uniqueness => Boolean. • Write your Own Validations class User < ActiveRecord::Base validate :my_custom_validation private def my_custom_validation self.errors.add(:coolness, "bad") unless self.cool == “supercool” end end @Schneems Thursday, June 16, 2011
  • 37. If & Unless puts “hello” if true >> “hello” puts “hello” if false >> nil puts “hello” unless true >> nil puts “hello” unless false >> “hello” @Schneems Thursday, June 16, 2011
  • 38. blank? & present? puts “hello”.blank? >> false puts “hello”.present? >> true puts false.blank? >> true puts nil.blank? >> true puts [].blank? >> true puts “”.blank? >> true @Schneems Thursday, June 16, 2011
  • 39. Testing • Test your code (or wish you did) • Makes upgrading and refactoring easier • Different Environments • production - live on the web • development - on your local computer • test - local clean environment @Schneems Thursday, June 16, 2011
  • 40. Testing • Unit Tests • Test individual methods against known inputs • Integration Tests • Test Multiple Controllers • Functional Tests • Test full stack M- V-C @Schneems Thursday, June 16, 2011
  • 41. Unit Testing • ActiveSupport::TestCase • Provides assert statements • assert true • assert (variable) • assert_same( obj1, obj2 ) • many more @Schneems Thursday, June 16, 2011
  • 42. Unit Testing • Run Unit Tests using: >> rake test:units RAILS_ENV=test @Schneems Thursday, June 16, 2011
  • 43. Unit Testing • Run Tests automatically the background • ZenTest • gem install autotest-standalone • Run: >> autotest @Schneems Thursday, June 16, 2011