SlideShare a Scribd company logo
Rails Summer of Code
                                     Week 2




Richard Schneeman - @ThinkBohemian
Rails - Week 2
                 • Ruby
                  • Hashes
                 • Classes
                    • Macros
                    • Methods
                  • Instances
                    • Methods
Richard Schneeman - @ThinkBohemian
Ruby
            • Hashes - (Like a Struct)
             • Key - Value Pairs - Different DataTypes Ok
               hash = {:a => 100, :b => “hello”}
               >> hash[:a]
                => 100
               >> hash[:b]
                => hello
               >> hash.keys
                => [:b, :a]

Richard Schneeman - @ThinkBohemian
Ruby
            • Hashes in method parameters
             • options (a hash) is optional parameter
               def myMethod(variable, options = {})
                  puts variable
                  options.keys.each do |key|
                    puts options[key]
                  end
               end

               >> myMethod(“Hi”)
                 => Hi
               >> myMethod(“Hi”, :a => “hello” , “there”)
                 => Hi
                    Hello
                    There
Richard Schneeman - @ThinkBohemian
Hashes in Rails
          • Used heavily
           • options (a hash) is optional parameter




        Rails API:   (ActionView::Helpers::FormHelper) text_area
Richard Schneeman - @ThinkBohemian
Hashes in Rails
          • Used heavily
           • options (a hash) is optional parameter




        Rails API:   (ActionView::Helpers::FormHelper) text_area
Richard Schneeman - @ThinkBohemian
Ruby
            • Objects don’t have attributes
             • Need getter & setter methods
                class MyClass
                   def myAttribute=(value)
                      @myAttribute = value
                   end

                  def myAttribute
                     @myAttribute
                  end
                end
                >> object = MyClass.new
                >> object.myAttribute = “foo”
                >> object.myAttribute
                  => “foo”

Richard Schneeman - @ThinkBohemian
Ruby
            • Ruby gives us Class Macros !!
             • Example: attr_accessor
                class MyClass
                   attr_accessor :myAttribute
                end

                >> object = MyClass.new
                >> object.myAttribute = “foo”
                >> object.myAttribute
                  => “foo”




Richard Schneeman - @ThinkBohemian
Ruby
            • Class Methods
             • (methods that can be run on the class)
                class My_class
                  def myInstanceMethod(value)
              
      puts value
                  end
              
                  def self.myClassMethod(value)
              
     puts value
                  end
                end


                My_class.myClassMethod("foo")
                => "foo"

Richard Schneeman - @ThinkBohemian
Ruby
            • Class Methods
             • (methods that can be run on the class)
                class My_class
                  def myInstanceMethod(value)
              
      puts value
                  end
              
                  def self.myClassMethod(value)
              
     puts value
                  end
                end


                My_class.myClassMethod("foo")
                => "foo"

Richard Schneeman - @ThinkBohemian
Ruby
         • Instance Methods
                class My_class
                  def myInstanceMethod(value)
              
      puts value
                  end
              
                  def self.myClassMethod(value)
              
     puts value
                  end
                end

       >> myInstance = My_class.new
       >> myInstance.myInstanceMethod("foo")
         => “foo”
       >> myInstance.myClassMethod(“bar”)
         => undefined method ‘myClassMethod’ for #<My_class:0x100124d18>


Richard Schneeman - @ThinkBohemian
Ruby
         • Instance Methods
                class My_class
                  def myInstanceMethod(value)
              
      puts value
                  end
              
                  def self.myClassMethod(value)
              
     puts value
                  end
                end

       >> myInstance = My_class.new
       >> myInstance.myInstanceMethod("foo")
         => “foo”
       >> myInstance.myClassMethod(“bar”)
         => undefined method ‘myClassMethod’ for #<My_class:0x100124d18>


Richard Schneeman - @ThinkBohemian
Ruby
         • Instance Methods
                class My_class
                  def myInstanceMethod(value)
              
      puts value
                  end
              
                  def self.myClassMethod(value)
              
     puts value
                  end
                end

       >> myInstance = My_class.new
       >> myInstance.myInstanceMethod("foo")
         => “foo”
       >> myInstance.myClassMethod(“bar”)
         => undefined method ‘myClassMethod’ for #<My_class:0x100124d18>


Richard Schneeman - @ThinkBohemian
Ruby
                • Class Methods               class Dog

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

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

                                              end




Richard Schneeman - @ThinkBohemian
Ruby
                • Class Methods               class Dog

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

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

                                              end




Richard Schneeman - @ThinkBohemian
Ruby
            • attr_accessor is a Class method
                attr_accessor :myAttribute



                               Can be defined as:

                def self.attr_accessor(value)
                   ...
                end


                                           cool !

Richard Schneeman - @ThinkBohemian
Rails - Week 2
                 • Code Generation
                  • Migrations
                  • Scaffolding
                 • Validation
                 • Testing (Rspec AutoTest)

Richard Schneeman - @ThinkBohemian
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)
Richard Schneeman - @ThinkBohemian
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




Richard Schneeman - @ThinkBohemian
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




Richard Schneeman - @ThinkBohemian
Migrations
        •   Creates a Table named post    def self.up
                                           create_table   :post do |t|
        •   Adds Columns                      t.string
                                              t.string
                                                          :name
                                                          :title

            •
                                              t.text      :content
                Name, Title, Content        end
                                          end

            •   created_at & updated_at
                added automatically




Richard Schneeman - @ThinkBohemian
Migrations
        •   Creates a Table named post    def self.up
                                           create_table   :post do |t|
        •   Adds Columns                      t.string
                                              t.string
                                                          :name
                                                          :title

            •
                                              t.text      :content
                Name, Title, Content        end
                                          end

            •   created_at & updated_at
                added automatically




Richard Schneeman - @ThinkBohemian
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




Richard Schneeman - @ThinkBohemian
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




Richard Schneeman - @ThinkBohemian
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




Richard Schneeman - @ThinkBohemian
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




Richard Schneeman - @ThinkBohemian
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




Richard Schneeman - @ThinkBohemian
Migrations
                 •   Made a mistake? Issue a database Ctrl + Z !


                 >> rake db:rollback

                 •   Runs last “down” migration


                              def self.down
                                 drop_table :system_settings
                               end




Richard Schneeman - @ThinkBohemian
Scaffolding
                 •   Generate Model, View, and Controller


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


                     •   models/post.rb

                     •   controllers/posts_controller.rb

                     •   views/post/{ index.html, show.html, new.html, create.html }




Richard Schneeman - @ThinkBohemian
Rails - Validations
                 •     Check your parameters before save

                      •   Provided by ActiveModel

                          •   Utilized by ActiveRecord

                     class Person < ActiveRecord::Base
                       validates :title, :presence => true, :title => true
                     end




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




Richard Schneeman - @ThinkBohemian
Rails - Validations
               Can use ActiveModel without Rails

                   class Person
                     include ActiveModel::Validations
                     attr_accessor :title
                     validates :title, :presence => true, :title => true
                   end




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




Richard Schneeman - @ThinkBohemian
Rails - Validations
                 •       Use Rail’s built in Validations
                     #   :acceptance => Boolean.
                     #   :confirmation => Boolean.
                     #   :exclusion => { :in => Ennumerable }.
                     #   :inclusion => { :in => Ennumerable }.
                     #   :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(:password, "Custom Message") unless self.property.present?
             end
         end


Richard Schneeman - @ThinkBohemian
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
Richard Schneeman - @ThinkBohemian
Testing
         • Unit Tests
          • Test individual methods against known inputs
         • Integration Tests
          • Test Multiple Controllers
         • Functional Tests
          • Test full stack M- V-C
Richard Schneeman - @ThinkBohemian
Unit Testing
            • ActiveSupport::TestCase
            • Provides assert statements
             • assert true
             • assert (variable)
             • assert_same( obj1, obj2 )
             • many more
Richard Schneeman - @ThinkBohemian
Unit Testing
            • Run Unit Tests using:
                   >> rake test:units RAILS_ENV=test




Richard Schneeman - @ThinkBohemian
Unit Testing
            • Run Tests automatically the background
             • ZenTest
               • sudo gem install ZenTest
               • Run:
                              >> autotest




Richard Schneeman - @ThinkBohemian
Questions?




Richard Schneeman - @ThinkBohemian

More Related Content

PDF
Rails 3 Beginner to Builder 2011 Week 2
PDF
Rails 3 Beginner to Builder 2011 Week 3
PDF
Introduction to Swift 2
KEY
Static or Dynamic Typing? Why not both?
PPT
Rapid Application Development using Ruby on Rails
PPTX
Code for Startup MVP (Ruby on Rails) Session 2
PDF
The Dark Art of Rails Plugins (2008)
PDF
jQuery-1-Ajax
Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 3
Introduction to Swift 2
Static or Dynamic Typing? Why not both?
Rapid Application Development using Ruby on Rails
Code for Startup MVP (Ruby on Rails) Session 2
The Dark Art of Rails Plugins (2008)
jQuery-1-Ajax

What's hot (17)

PPTX
Ruby :: Training 1
PDF
Ruby Xml Mapping
PDF
Php Crash Course - Macq Electronique 2010
PDF
Swift Basics
PDF
Swift in SwiftUI
PDF
오브젝트C(pdf)
PPTX
Introduction to python
KEY
Scala For Java Programmers
PDF
From android/java to swift (3)
PDF
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
PDF
Quick swift tour
PDF
Scala. Inception.
PDF
Nikita Popov "What’s new in PHP 8.0?"
PDF
RoR_2_Ruby
PPTX
From Ruby to Scala
KEY
Rails for PHP Developers
PDF
Selfish presentation - ruby internals
Ruby :: Training 1
Ruby Xml Mapping
Php Crash Course - Macq Electronique 2010
Swift Basics
Swift in SwiftUI
오브젝트C(pdf)
Introduction to python
Scala For Java Programmers
From android/java to swift (3)
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
Quick swift tour
Scala. Inception.
Nikita Popov "What’s new in PHP 8.0?"
RoR_2_Ruby
From Ruby to Scala
Rails for PHP Developers
Selfish presentation - ruby internals
Ad

Similar to UT on Rails3 2010- Week 2 (6)

KEY
Ruby objects
KEY
Metaprogramming Primer (Part 1)
PPTX
Python 2. classes- cruciql for students objects1.pptx
PDF
Marc’s (bio)perl course
KEY
Rails3 Summer of Code 2010- Week 5
PDF
Metaprogramming in Ruby
Ruby objects
Metaprogramming Primer (Part 1)
Python 2. classes- cruciql for students objects1.pptx
Marc’s (bio)perl course
Rails3 Summer of Code 2010- Week 5
Metaprogramming in Ruby
Ad

More from Richard Schneeman (10)

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

Recently uploaded (20)

PPTX
cấu trúc sử dụng mẫu Cause - Effects.pptx
PDF
Elle Lalli on The Role of Emotional Intelligence in Entrepreneurship
PPTX
Learn about numerology and do tarot reading
PPTX
Learn how to use Portable Grinders Safely
PPTX
Learn numerology content and join tarot reading
PDF
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
PPTX
diasspresentationndkcnskndncelklkfndc.pptx
PDF
Quiet Wins: Why the Silent Fish Survives.pdf
PPTX
How to Deal with Imposter Syndrome for Personality Development?
PPTX
SELF ASSESSMENT -SNAPSHOT.pptx an index of yourself by Dr NIKITA SHARMA
PPTX
Commmunication in Todays world- Principles and Barriers
PDF
The Zeigarnik Effect by Meenakshi Khakat.pdf
PDF
Red Light Wali Muskurahat – A Heart-touching Hindi Story
PPTX
Chapter-7-The-Spiritual-Self-.pptx-First
PPTX
Identity Development in Adolescence.pptx
PDF
My 'novel' Account of Human Possibility pdf.pdf
PDF
Top 10 Visionary Entrepreneurs to Watch in 2025
PPTX
Learn how to prevent Workplace Incidents?
PPTX
Understanding the Self power point presentation
DOCX
Boost your energy levels and Shred Weight
cấu trúc sử dụng mẫu Cause - Effects.pptx
Elle Lalli on The Role of Emotional Intelligence in Entrepreneurship
Learn about numerology and do tarot reading
Learn how to use Portable Grinders Safely
Learn numerology content and join tarot reading
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
diasspresentationndkcnskndncelklkfndc.pptx
Quiet Wins: Why the Silent Fish Survives.pdf
How to Deal with Imposter Syndrome for Personality Development?
SELF ASSESSMENT -SNAPSHOT.pptx an index of yourself by Dr NIKITA SHARMA
Commmunication in Todays world- Principles and Barriers
The Zeigarnik Effect by Meenakshi Khakat.pdf
Red Light Wali Muskurahat – A Heart-touching Hindi Story
Chapter-7-The-Spiritual-Self-.pptx-First
Identity Development in Adolescence.pptx
My 'novel' Account of Human Possibility pdf.pdf
Top 10 Visionary Entrepreneurs to Watch in 2025
Learn how to prevent Workplace Incidents?
Understanding the Self power point presentation
Boost your energy levels and Shred Weight

UT on Rails3 2010- Week 2

  • 1. Rails Summer of Code Week 2 Richard Schneeman - @ThinkBohemian
  • 2. Rails - Week 2 • Ruby • Hashes • Classes • Macros • Methods • Instances • Methods Richard Schneeman - @ThinkBohemian
  • 3. Ruby • Hashes - (Like a Struct) • Key - Value Pairs - Different DataTypes Ok hash = {:a => 100, :b => “hello”} >> hash[:a] => 100 >> hash[:b] => hello >> hash.keys => [:b, :a] Richard Schneeman - @ThinkBohemian
  • 4. Ruby • Hashes in method parameters • options (a hash) is optional parameter def myMethod(variable, options = {}) puts variable options.keys.each do |key| puts options[key] end end >> myMethod(“Hi”) => Hi >> myMethod(“Hi”, :a => “hello” , “there”) => Hi Hello There Richard Schneeman - @ThinkBohemian
  • 5. Hashes in Rails • Used heavily • options (a hash) is optional parameter Rails API: (ActionView::Helpers::FormHelper) text_area Richard Schneeman - @ThinkBohemian
  • 6. Hashes in Rails • Used heavily • options (a hash) is optional parameter Rails API: (ActionView::Helpers::FormHelper) text_area Richard Schneeman - @ThinkBohemian
  • 7. Ruby • Objects don’t have attributes • Need getter & setter methods class MyClass def myAttribute=(value) @myAttribute = value end def myAttribute @myAttribute end end >> object = MyClass.new >> object.myAttribute = “foo” >> object.myAttribute => “foo” Richard Schneeman - @ThinkBohemian
  • 8. Ruby • Ruby gives us Class Macros !! • Example: attr_accessor class MyClass attr_accessor :myAttribute end >> object = MyClass.new >> object.myAttribute = “foo” >> object.myAttribute => “foo” Richard Schneeman - @ThinkBohemian
  • 9. Ruby • Class Methods • (methods that can be run on the class) class My_class def myInstanceMethod(value) puts value end def self.myClassMethod(value) puts value end end My_class.myClassMethod("foo") => "foo" Richard Schneeman - @ThinkBohemian
  • 10. Ruby • Class Methods • (methods that can be run on the class) class My_class def myInstanceMethod(value) puts value end def self.myClassMethod(value) puts value end end My_class.myClassMethod("foo") => "foo" Richard Schneeman - @ThinkBohemian
  • 11. Ruby • Instance Methods class My_class def myInstanceMethod(value) puts value end def self.myClassMethod(value) puts value end end >> myInstance = My_class.new >> myInstance.myInstanceMethod("foo") => “foo” >> myInstance.myClassMethod(“bar”) => undefined method ‘myClassMethod’ for #<My_class:0x100124d18> Richard Schneeman - @ThinkBohemian
  • 12. Ruby • Instance Methods class My_class def myInstanceMethod(value) puts value end def self.myClassMethod(value) puts value end end >> myInstance = My_class.new >> myInstance.myInstanceMethod("foo") => “foo” >> myInstance.myClassMethod(“bar”) => undefined method ‘myClassMethod’ for #<My_class:0x100124d18> Richard Schneeman - @ThinkBohemian
  • 13. Ruby • Instance Methods class My_class def myInstanceMethod(value) puts value end def self.myClassMethod(value) puts value end end >> myInstance = My_class.new >> myInstance.myInstanceMethod("foo") => “foo” >> myInstance.myClassMethod(“bar”) => undefined method ‘myClassMethod’ for #<My_class:0x100124d18> Richard Schneeman - @ThinkBohemian
  • 14. Ruby • Class Methods class Dog • Have self def self.find(name) ... end • Instance Methods def wag_tail(frequency) ... • Don’t (Have self) end end Richard Schneeman - @ThinkBohemian
  • 15. Ruby • Class Methods class Dog • Have self def self.find(name) ... end • Instance Methods def wag_tail(frequency) ... • Don’t (Have self) end end Richard Schneeman - @ThinkBohemian
  • 16. Ruby • attr_accessor is a Class method attr_accessor :myAttribute Can be defined as: def self.attr_accessor(value) ... end cool ! Richard Schneeman - @ThinkBohemian
  • 17. Rails - Week 2 • Code Generation • Migrations • Scaffolding • Validation • Testing (Rspec AutoTest) Richard Schneeman - @ThinkBohemian
  • 18. 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) Richard Schneeman - @ThinkBohemian
  • 19. 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 Richard Schneeman - @ThinkBohemian
  • 20. 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 Richard Schneeman - @ThinkBohemian
  • 21. Migrations • Creates a Table named post def self.up create_table :post do |t| • Adds Columns t.string t.string :name :title • t.text :content Name, Title, Content end end • created_at & updated_at added automatically Richard Schneeman - @ThinkBohemian
  • 22. Migrations • Creates a Table named post def self.up create_table :post do |t| • Adds Columns t.string t.string :name :title • t.text :content Name, Title, Content end end • created_at & updated_at added automatically Richard Schneeman - @ThinkBohemian
  • 23. 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 Richard Schneeman - @ThinkBohemian
  • 24. 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 Richard Schneeman - @ThinkBohemian
  • 25. 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 Richard Schneeman - @ThinkBohemian
  • 26. 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 Richard Schneeman - @ThinkBohemian
  • 27. 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 Richard Schneeman - @ThinkBohemian
  • 28. Migrations • Made a mistake? Issue a database Ctrl + Z ! >> rake db:rollback • Runs last “down” migration def self.down drop_table :system_settings end Richard Schneeman - @ThinkBohemian
  • 29. Scaffolding • Generate Model, View, and Controller >> scaffold Post name:string title:string content:text • models/post.rb • controllers/posts_controller.rb • views/post/{ index.html, show.html, new.html, create.html } Richard Schneeman - @ThinkBohemian
  • 30. Rails - Validations • Check your parameters before save • Provided by ActiveModel • Utilized by ActiveRecord class Person < ActiveRecord::Base validates :title, :presence => true, :title => true end bob = Person.create(:title => nil) >> bob.valid? => false >> bob.save => false Richard Schneeman - @ThinkBohemian
  • 31. Rails - Validations Can use ActiveModel without Rails class Person include ActiveModel::Validations attr_accessor :title validates :title, :presence => true, :title => true end bob = Person.create(:title => nil) >> bob.valid? => false >> bob.save => false Richard Schneeman - @ThinkBohemian
  • 32. Rails - Validations • Use Rail’s built in Validations # :acceptance => Boolean. # :confirmation => Boolean. # :exclusion => { :in => Ennumerable }. # :inclusion => { :in => Ennumerable }. # :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(:password, "Custom Message") unless self.property.present? end end Richard Schneeman - @ThinkBohemian
  • 33. 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 Richard Schneeman - @ThinkBohemian
  • 34. Testing • Unit Tests • Test individual methods against known inputs • Integration Tests • Test Multiple Controllers • Functional Tests • Test full stack M- V-C Richard Schneeman - @ThinkBohemian
  • 35. Unit Testing • ActiveSupport::TestCase • Provides assert statements • assert true • assert (variable) • assert_same( obj1, obj2 ) • many more Richard Schneeman - @ThinkBohemian
  • 36. Unit Testing • Run Unit Tests using: >> rake test:units RAILS_ENV=test Richard Schneeman - @ThinkBohemian
  • 37. Unit Testing • Run Tests automatically the background • ZenTest • sudo gem install ZenTest • Run: >> autotest Richard Schneeman - @ThinkBohemian