SlideShare una empresa de Scribd logo
1 de 44
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Más de 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
 

Más de 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
 

Último

How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryCeline George
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptxPoojaSen20
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxMohamed Rizk Khodair
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhleson0603
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Denish Jangid
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the lifeNitinDeodare
 

Último (20)

Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
Mattingly "AI and Prompt Design: LLMs with Text Classification and Open Source"
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 Inventory
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 

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