Rails 3 Beginner to Builder 2011 Week 2

44
June, 2011 Beginner to Builder Week 2 Richard Schneeman @schneems Thursday, June 16, 2011

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-2011

Transcript of Rails 3 Beginner to Builder 2011 Week 2

Page 1: Rails 3 Beginner to Builder 2011 Week 2

June, 2011

Beginner to BuilderWeek 2Richard Schneeman@schneems

Thursday, June 16, 2011

Page 2: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Rails - Week 2• Ruby

• Hashes & default params

• Classes

• Macros

• Methods

• Instances

• Methods

Thursday, June 16, 2011

Page 3: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Rails - Week 2• Code Generation

• Migrations

• Scaffolding

• Validation

• Testing (Rspec AutoTest)

Thursday, June 16, 2011

Page 4: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 5: Rails 3 Beginner to Builder 2011 Week 2

• 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

Page 6: Rails 3 Beginner to Builder 2011 Week 2

• 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

Page 7: Rails 3 Beginner to Builder 2011 Week 2

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

Page 8: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 9: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 10: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Ruby• Objects don’t have attributes

• Only methods

• Need getter & setter methods

Thursday, June 16, 2011

Page 11: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 12: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 13: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 14: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 15: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 16: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 17: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 18: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 19: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 20: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 21: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Rails - Week 2• Code Generation

• Migrations

• Scaffolding

• Validation

• Testing (Rspec AutoTest)

Thursday, June 16, 2011

Page 22: Rails 3 Beginner to Builder 2011 Week 2

• 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

Page 23: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Database Backed Models• Store and access massive amounts of

data

• Table

• columns (name, type, modifier)

• rows

Table: Users

Thursday, June 16, 2011

Page 24: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Create Schema• Create Schema

• Multiple machines

Enter...Migrations

Thursday, June 16, 2011

Page 25: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 26: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 27: Rails 3 Beginner to Builder 2011 Week 2

• 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

Page 28: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 29: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 30: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 31: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 32: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 33: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 34: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 35: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 36: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 37: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 38: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

blank? & present?puts “hello”.blank?>> falseputs “hello”.present?>> trueputs false.blank?>> trueputs nil.blank?>> trueputs [].blank?>> trueputs “”.blank?>> true

Thursday, June 16, 2011

Page 39: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 40: Rails 3 Beginner to Builder 2011 Week 2

@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

Page 41: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Unit Testing• ActiveSupport::TestCase

• Provides assert statements

• assert true

• assert (variable)

• assert_same( obj1, obj2 )

• many more

Thursday, June 16, 2011

Page 42: Rails 3 Beginner to Builder 2011 Week 2

• Run Unit Tests using:

@Schneems

>> rake test:units RAILS_ENV=test

Unit Testing

Thursday, June 16, 2011

Page 43: Rails 3 Beginner to Builder 2011 Week 2

• Run Tests automatically the background

• ZenTest

• gem install autotest-standalone

• Run:

@Schneems

>> autotest

Unit Testing

Thursday, June 16, 2011

Page 44: Rails 3 Beginner to Builder 2011 Week 2

@Schneems

Questions?

Thursday, June 16, 2011