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 1Pavel Tyk
 
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 5Richard Schneeman
 
DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻DevLOVE Beautiful Development - 第一幕 陽の巻
DevLOVE Beautiful Development - 第一幕 陽の巻都元ダイスケ Miyamoto
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
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のマクロに実用例から触れてみよう!scalaconfjp
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scalatod esking
 
Rails for PHP Developers
Rails for PHP DevelopersRails for PHP Developers
Rails for PHP DevelopersRobert Dempsey
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan 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

Bc phase one_session10
Bc phase one_session10Bc phase one_session10
Bc phase one_session10Giberto Alviso
 
PEShare.co.uk Shared Resource
PEShare.co.uk Shared ResourcePEShare.co.uk Shared Resource
PEShare.co.uk Shared Resourcepeshare.co.uk
 
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 6Richard Schneeman
 
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 1Richard Schneeman
 
Skill of Observation
Skill of ObservationSkill of Observation
Skill of ObservationAkshat Tewari
 
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!!Lucas Brasilino
 
Teaching with limited resources checkpoint
Teaching with limited resources checkpointTeaching with limited resources checkpoint
Teaching with limited resources checkpointuasilanguage
 
Minicurso JSON & Ajax
Minicurso JSON & AjaxMinicurso JSON & Ajax
Minicurso JSON & AjaxWilker Iceri
 
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 studentsNicolas Antonio Villalonga Rojas
 
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 TenseMd. Abdul Kader
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentationadamcookeuk
 
Mini lesson on past tense simple
Mini lesson on past tense simpleMini lesson on past tense simple
Mini lesson on past tense simplepaulbradigan
 

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

Scaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLScaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLRichard Schneeman
 
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 8Richard Schneeman
 
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 5Richard 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 6Richard 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

KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

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