rails 3 beginner to builder 2011 week 2
DESCRIPTION
This is the 2nd of 8 presentations given at University of Texas during my Beginner to Builder Rails 3 Class. For more info and the whole series including video presentations at my blog: http://schneems.tumblr.com/tagged/Rails-3-beginner-to-builder-2011TRANSCRIPT
June, 2011
Beginner to BuilderWeek 2Richard Schneeman@schneems
Thursday, June 16, 2011
@Schneems
Rails - Week 2• Ruby
• Hashes & default params
• Classes
• Macros
• Methods
• Instances
• Methods
Thursday, June 16, 2011
@Schneems
Rails - Week 2• Code Generation
• Migrations
• Scaffolding
• Validation
• Testing (Rspec AutoTest)
Thursday, June 16, 2011
@Schneems
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"
Ruby - Default Params
Thursday, June 16, 2011
• Hashes - (Like a Struct)
• Key - Value Pairs - Different DataTypes Ok
@Schneems
hash = {:a => 100, “b” => “hello”}
>> hash[:a]
=> 100
>> hash[“b”]
=> hello
>> hash.keys
=> [“b”, :a]
Ruby
Thursday, June 16, 2011
• Hashes in method parameters
• options (a hash) is optional parameter
• has a default value
@Schneems
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'"
Ruby - Default Params
Thursday, June 16, 2011
Ruby - Default Params
@Schneems
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'"
Thursday, June 16, 2011
@Schneems
Hashes in Rails• Used heavily as parameters
• options (a hash) is optional parameter
Rails API: (ActionView::Helpers::FormHelper) text_area
Thursday, June 16, 2011
@Schneems
Hashes in Rails• Used heavily as parameters
• options (a hash) is optional parameter
Rails API: (ActionView::Helpers::FormHelper) text_area
Thursday, June 16, 2011
@Schneems
Ruby• Objects don’t have attributes
• Only methods
• Need getter & setter methods
Thursday, June 16, 2011
@Schneems
Attributesclass 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”
Thursday, June 16, 2011
@Schneems
class Car
attr_accessor :color
end
>> my_car = Car.new
>> my_car.color = “hot_pink”
>> my_car.color
=> “hot_pink”
Ruby - attr_accessor
Thursday, June 16, 2011
@Schneems
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”
Attributes
Thursday, June 16, 2011
@Schneems
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
Ruby - Self
Thursday, June 16, 2011
@Schneems
Ruby - Class Methodsclass MyClass
def self.my_method_1(value)
puts value
end
end
MyClass.my_method_1("foo")
>> "foo"
Thursday, June 16, 2011
@Schneems
Ruby - Class Methodsclass 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
Thursday, June 16, 2011
@Schneems
Ruby - Instance Methodsclass 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
Thursday, June 16, 2011
@Schneems
Ruby - Instance Methodsclass MyClass
def my_method_2(value)
puts value
end
end
my_instance = MyClass.new
my_instance.my_method_2("foo")
>> "foo"
Thursday, June 16, 2011
@Schneems
class Dog
def self.find(name)
...
end
def wag_tail(frequency)
...
end
end
Ruby• Class Methods
• Have self
• Instance Methods
• Don’t (Have self)
Thursday, June 16, 2011
@Schneems
class Dog
attr_accessor :fur_color
end
Ruby• attr_accessor is a Class method
Can be defined as:
cool !
class Dog
def self.attr_accessor(value)
#...
end
end
Thursday, June 16, 2011
@Schneems
Rails - Week 2• Code Generation
• Migrations
• Scaffolding
• Validation
• Testing (Rspec AutoTest)
Thursday, June 16, 2011
• Generate Model, View, and Controller & Migration
• 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
>> rails generate scaffold
Post name:string title:string content:text
Scaffolding
Thursday, June 16, 2011
@Schneems
Database Backed Models• Store and access massive amounts of
data
• Table
• columns (name, type, modifier)
• rows
Table: Users
Thursday, June 16, 2011
@Schneems
Create Schema• Create Schema
• Multiple machines
Enter...Migrations
Thursday, June 16, 2011
@Schneems
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 endend
Migrations• Create your data structure in your Database
• Set a database’s schema
migrate/create_post.rb
Thursday, June 16, 2011
@Schneems
>> rake db:migrate
Migrations• Get your data structure into your database
• Runs all “Up” migrations
def self.up
create_table :post do |t|
t.string :name
t.string :title
t.text :content
end
end
Thursday, June 16, 2011
• Creates a Table named post
• Adds Columns
• Name, Title, Content
• created_at & updated_at added automatically
@Schneems
Migrations def self.up create_table :post do |t| t.string :name t.string :title t.text :content end end
def self.up
create_table :post do |t|
t.string :name
t.string :title
t.text :content
end
end
Thursday, June 16, 2011
@Schneems
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
Thursday, June 16, 2011
@Schneems
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
Thursday, June 16, 2011
@Schneems
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
Thursday, June 16, 2011
@Schneems
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
Thursday, June 16, 2011
@Schneems
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
Thursday, June 16, 2011
@Schneems
>> rake db:rollback
Migrations• Made a mistake? Issue a database Ctrl + Z !
• Runs last “down” migration
def self.down
drop_table :system_settings
end
Thursday, June 16, 2011
@Schneems
class Person < ActiveRecord::Base
validates :title, :presence => true
end
Rails - Validations• Check your parameters before save
• Provided by ActiveModel
• Utilized by ActiveRecord
bob = Person.create(:title => nil)
>> bob.valid?
=> false
>> bob.save
=> false
Thursday, June 16, 2011
@Schneems
Rails - ValidationsCan 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
Thursday, June 16, 2011
@Schneems
# :acceptance => Boolean.# :confirmation => Boolean.# :exclusion => { :in => Enumerable }.# :inclusion => { :in => Enumerable }.# :format => { :with => Regexp, :on => :create }.# :length => { :maximum => Fixnum }.# :numericality => Boolean.# :presence => Boolean.# :uniqueness => Boolean.
Rails - Validations• Use Rail’s built in Validations
• Write your Own Validationsclass User < ActiveRecord::Base validate :my_custom_validation private def my_custom_validation self.errors.add(:coolness, "bad") unless self.cool == “supercool” endend
Thursday, June 16, 2011
@Schneems
If & Unlessputs “hello” if true>> “hello”puts “hello” if false>> nil
puts “hello” unless true>> nilputs “hello” unless false>> “hello”
Thursday, June 16, 2011
@Schneems
blank? & present?puts “hello”.blank?>> falseputs “hello”.present?>> trueputs false.blank?>> trueputs nil.blank?>> trueputs [].blank?>> trueputs “”.blank?>> true
Thursday, June 16, 2011
@Schneems
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
Thursday, June 16, 2011
@Schneems
Testing• Unit Tests
• Test individual methods against known inputs
• Integration Tests
• Test Multiple Controllers
• Functional Tests
• Test full stack M- V-C
Thursday, June 16, 2011
@Schneems
Unit Testing• ActiveSupport::TestCase
• Provides assert statements
• assert true
• assert (variable)
• assert_same( obj1, obj2 )
• many more
Thursday, June 16, 2011
• Run Unit Tests using:
@Schneems
>> rake test:units RAILS_ENV=test
Unit Testing
Thursday, June 16, 2011
• Run Tests automatically the background
• ZenTest
• gem install autotest-standalone
• Run:
@Schneems
>> autotest
Unit Testing
Thursday, June 16, 2011
@Schneems
Questions?
Thursday, June 16, 2011