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

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
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 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 

Recently uploaded (20)

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
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🔝
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
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 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.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