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

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
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
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 

Recently uploaded (20)

ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
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
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.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