SlideShare una empresa de Scribd logo
1 de 31
Descargar para leer sin conexión
Rails3 changesets
    ihower@gmail.com
        2010/8/17
About Me
•              a.k.a. ihower
    •   http://ihower.tw

    •   http://twitter.com/ihower

• Rails Developer since 2006
• The Organizer of Ruby Taiwan Community
 • http://ruby.tw
 • http://rubyconf.tw
Agenda
•   Bundler
•   ActiveRecord: New Query API
•   ActiveRecord: New Validation API
•   Views: XSS, Block Helper and JavaScript
•   I18n
•   New Routing API
•   New ActionMailer
•   Metal
1. Bundler
http://ihower.tw/blog/archives/4464
Gemfile
#
gem "rails", "3.0.0.rc"

#     require                   :require
gem "sqlite3-ruby", :require => "sqlite3"

#       Git                    branch, tag    ref
gem 'authlogic', :git => 'git://github.com/odorcicd/authlogic.git',
                          :branch => 'rails3'

#
gem "rails", :path => '/Users/ihower/github/rails'

# Group
group :test do
  gem "rspec-rails", ">= 2.0.0.beta.8"
  gem "webrat"
end
2. AR Query API
AR queries (1)
                     method chaining


# Rails 2
users = User.find(:all, :conditions => { :name =>
'ihower' }, :limit => 10, :order => 'age')

# Rails 3
users = User.where(:name => 'ihower').limit(20).order('age')
AR queries (2)
      Unify finders, named_scope, with_scope to Relation
# Rails 2
users = User
users = users.some_named_scope if params[:some]
sort = params[:sort] || "id"
conditions = {}

if params[:name]
  conditions = User.merge_conditions( conditions, { :name => params[:name] } )
end

if params[:age]
  conditions = User.merge_conditions( conditions, { :age => params[:age] } )
end

find_conditions = { :conditions => conditions, :order => "#{sort} #{dir}" }
sort = params[:sort] || "id"

users = users.find(:all, :conditions => conditions, :order => sort )
AR queries (2)
Unify finders, named_scope, with_scope to Relation


# Rails   3
users =   User
users =   users.some_scope if params[:some]
users =   users.where( :name => params[:name] ) if params[:name]
users =   users.where( :age => params[:age] ) if params[:age]
users =   users.order( params[:sort] || "id" )
AR queries (3)
Using class methods instead of scopes when you need lambda
    # Rails 3
    class Product < ActiveRecord::Base

      scope :discontinued, where(:discontinued => true)
      scope :cheaper_than, lambda { |price| where("price < ?", price) }

    end

    # Rails 3, prefer this way more
    class Product < ActiveRecord::Base

      scope :discontinued, where(:discontinued => true)

      def self.cheaper_than(price)
        where("price < ?", price)
      end

    end
3. AR Validation API
AR validation (1)
# Rails 2
class User < ActiveRecord::Base
  validates_presence_of :email
  validates_uniqueness_of :email
  validates_format_of :email, :with => /^[wd]+$/ :on => :create, :message =>
"is invalid"
end

# Rails 3
class User < ActiveRecord::Base
  validates :email,
            :presence => true,
            :uniqueness => true,
            :format => { :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i }
end




                                    http://asciicasts.com/episodes/211-validations-in-rails-3
AR validation (2)
                           custom validator

# Rails 3
class User < ActiveRecord::Base
  validates :email, :presence => true,
                    :uniqueness => true,
                    :email_format => true
end

class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || "is not formatted
properly")
    end
  end
end
4.Views
Secure XSS
Rails3 will automatically escape any string that does not
            originate from inside of Rails itself

            # Rails2
            <%=h @person.title %>

            # Rails3
            <%=@person.title %>

            # unescape string
            <%= @person.title.html_safe %>
            <%= raw @person.title %>
Unobtrusive JavaScript
  # Rails 2
  link_to_remote "Name", url_path
  # Rails 3
  link_to "Name", url_path, :remote => true

  # Rails 2
  remote_form_for @article do
  end
  # Rails 3
  form_for @article, :remote => true do
  end
You can change rails.js
  to jQuery version
   http://ihower.tw/blog/archives/3917
consistent <%= %>
  # Rails 2
  <% form_for @article do %>
  end

  <% content_for :sidebar do %>
  <% end %>

  # Rails 3
  <%= form_for @article do %>
  end

  <%= content_for :sidebar do %>
  <% end %>
consistent <%= %> (2)
   # Rails2
   <% my_helper do %>
     blah
   <% end %>

   # Rails2 Helper
   def my_helper
     concat("header")
     yield
     concat("footer")
   end

   # or
   def my_helper(&block)
       tmp = with_output_buffer(&block)
       concat("header #{tmp} footer")
   end
consistent <%= %> (3)
   # Rails3
   <%= my_helper do %>
     blah
   <% end %>

   # Rails3 Helper
   def my_helper(&block)
     tmp = with_output_buffer(&block)
     "header #{tmp} footer"
   end
5. I18n
{{ }} becomes to %{}
6. Routing API
Routes
                            nice DSL
# Rails 2
map.resources :people, :member => { :dashboard => :get,
                                    :resend => :post,
                                    :upload => :put } do |people|
    people.resource :avatra
end

# Rails 3
resources :people do
    resource :avatar
    member do
        get :dashboard
        post :resend
        put :upload
    end
end
7. ActionMailer
ActionMailer
# Rails 2
class UserMailer < ActionMailer::Base

  def signup(user)
    recipients user.email
    from 'ihower@gmail.com'
    body :name => user.name
    subject "Signup"
  end

end

UserMailer.deliver_registration_confirmation(@user)
ActionMailer
# Rails 3
class UserMailer < ActionMailer::Base

  default :from => "ihower@gmail.com"

  def signup(user)
    @name = user.name
    mail(:to => user.email, :subject => "Signup" )
  end

end

UserMailer.registration_confirmation(@user).deliver
8. Metal
Removing Metal

• Use Rack middleware
• Use Rack endpoint in the router
 • you can inherit ActionController::Metal
    to gain controller’s feature
Yehuda’s benchmark
rps
2900    Rack
2200    config.middleware.use YourMiddleware
2000    Rails Route
1900    ActionController::Metal
1070    ActionController::Base
825     ActionController::Base     render :text
765     ActionController::Base     render :template
375     ActionController::Base     Template    Layout
Thanks.
More on http://ihower.tw/blog/archives/4590
                   and
         http://ihower.tw/rails3/

Más contenido relacionado

La actualidad más candente

Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à RubyMicrosoft
 
RubyConf Bangladesh 2017 - Elixir for Rubyists
RubyConf Bangladesh 2017 - Elixir for RubyistsRubyConf Bangladesh 2017 - Elixir for Rubyists
RubyConf Bangladesh 2017 - Elixir for RubyistsRuby Bangladesh
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 
Building Cloud Castles
Building Cloud CastlesBuilding Cloud Castles
Building Cloud CastlesBen Scofield
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stackPaul Bearne
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Umair Amjad
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers StealBen Scofield
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUGBen Scofield
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - IntroductionVagmi Mudumbai
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentNicolas Ledez
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsNeil Crookes
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroChristopher Pecoraro
 
Rails 3 ActiveRecord
Rails 3 ActiveRecordRails 3 ActiveRecord
Rails 3 ActiveRecordBlazing Cloud
 
AngularJS with Slim PHP Micro Framework
AngularJS with Slim PHP Micro FrameworkAngularJS with Slim PHP Micro Framework
AngularJS with Slim PHP Micro FrameworkBackand Cohen
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Vikas Chauhan
 
Bullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-FrameworkBullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-FrameworkVance Lucas
 

La actualidad más candente (20)

Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
RubyConf Bangladesh 2017 - Elixir for Rubyists
RubyConf Bangladesh 2017 - Elixir for RubyistsRubyConf Bangladesh 2017 - Elixir for Rubyists
RubyConf Bangladesh 2017 - Elixir for Rubyists
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
Building Cloud Castles
Building Cloud CastlesBuilding Cloud Castles
Building Cloud Castles
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers Steal
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUG
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
Rails 3 ActiveRecord
Rails 3 ActiveRecordRails 3 ActiveRecord
Rails 3 ActiveRecord
 
Rails3 way
Rails3 wayRails3 way
Rails3 way
 
AngularJS with Slim PHP Micro Framework
AngularJS with Slim PHP Micro FrameworkAngularJS with Slim PHP Micro Framework
AngularJS with Slim PHP Micro Framework
 
Getting Started-with-Laravel
Getting Started-with-LaravelGetting Started-with-Laravel
Getting Started-with-Laravel
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
Rack
RackRack
Rack
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2
 
Bullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-FrameworkBullet: The Functional PHP Micro-Framework
Bullet: The Functional PHP Micro-Framework
 

Destacado

T E C H N O L O GY OF CREATING
T E C H N O L O GY  OF CREATINGT E C H N O L O GY  OF CREATING
T E C H N O L O GY OF CREATINGEkonom
 
Idees Fotum Ville2 Marseille
Idees Fotum Ville2 MarseilleIdees Fotum Ville2 Marseille
Idees Fotum Ville2 Marseilleguest9ec3c75
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介Wen-Tien Chang
 
Modeli razvitka
Modeli razvitkaModeli razvitka
Modeli razvitkaEkonom
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On RailsWen-Tien Chang
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxWen-Tien Chang
 

Destacado (6)

T E C H N O L O GY OF CREATING
T E C H N O L O GY  OF CREATINGT E C H N O L O GY  OF CREATING
T E C H N O L O GY OF CREATING
 
Idees Fotum Ville2 Marseille
Idees Fotum Ville2 MarseilleIdees Fotum Ville2 Marseille
Idees Fotum Ville2 Marseille
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介
 
Modeli razvitka
Modeli razvitkaModeli razvitka
Modeli razvitka
 
Building Web Interface On Rails
Building Web Interface On RailsBuilding Web Interface On Rails
Building Web Interface On Rails
 
Ruby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 AjaxRuby on Rails : RESTful 和 Ajax
Ruby on Rails : RESTful 和 Ajax
 

Similar a Rails3 changesets

Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) RoundupWayne Carter
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Henry S
 
Ruby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineRuby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineNascenia IT
 
Rails3 for Rails2 developers
Rails3 for Rails2 developersRails3 for Rails2 developers
Rails3 for Rails2 developersalkeshv
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuLucas Renan
 
Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Clinton Dreisbach
 
QConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações WebQConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações WebFabio Akita
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyLaunchAny
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortegaarman o
 
Rails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowRails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowChris Oliver
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayConRuby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayConheikowebers
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
20120121 rbc rails_routing
20120121 rbc rails_routing20120121 rbc rails_routing
20120121 rbc rails_routingTakeshi AKIMA
 
Construindo APIs Usando Rails
Construindo APIs Usando RailsConstruindo APIs Usando Rails
Construindo APIs Usando RailsFernando Kakimoto
 

Similar a Rails3 changesets (20)

Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
 
Ruby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineRuby on Rails: Coding Guideline
Ruby on Rails: Coding Guideline
 
Rails3 for Rails2 developers
Rails3 for Rails2 developersRails3 for Rails2 developers
Rails3 for Rails2 developers
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
 
Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3
 
QConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações WebQConSP 2015 - Dicas de Performance para Aplicações Web
QConSP 2015 - Dicas de Performance para Aplicações Web
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
Rails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not KnowRails World 2023: Powerful Rails Features You Might Not Know
Rails World 2023: Powerful Rails Features You Might Not Know
 
Rail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendranRail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendran
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Scala active record
Scala active recordScala active record
Scala active record
 
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayConRuby on Rails Security Updated (Rails 3) at RailsWayCon
Ruby on Rails Security Updated (Rails 3) at RailsWayCon
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
20120121 rbc rails_routing
20120121 rbc rails_routing20120121 rbc rails_routing
20120121 rbc rails_routing
 
Construindo APIs Usando Rails
Construindo APIs Usando RailsConstruindo APIs Usando Rails
Construindo APIs Usando Rails
 

Más de Wen-Tien Chang

⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨Wen-Tien Chang
 
Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Wen-Tien Chang
 
A brief introduction to Machine Learning
A brief introduction to Machine LearningA brief introduction to Machine Learning
A brief introduction to Machine LearningWen-Tien Chang
 
淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2Wen-Tien Chang
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails TutorialWen-Tien Chang
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateWen-Tien Chang
 
Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Wen-Tien Chang
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事Wen-Tien Chang
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upWen-Tien Chang
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩Wen-Tien Chang
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Wen-Tien Chang
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0Wen-Tien Chang
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingWen-Tien Chang
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean StartupWen-Tien Chang
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事Wen-Tien Chang
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingWen-Tien Chang
 

Más de Wen-Tien Chang (20)

⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨⼤語⾔模型 LLM 應⽤開發入⾨
⼤語⾔模型 LLM 應⽤開發入⾨
 
Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛Ruby Rails 老司機帶飛
Ruby Rails 老司機帶飛
 
A brief introduction to Machine Learning
A brief introduction to Machine LearningA brief introduction to Machine Learning
A brief introduction to Machine Learning
 
淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2淺談 Startup 公司的軟體開發流程 v2
淺談 Startup 公司的軟體開發流程 v2
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
RSpec & TDD Tutorial
RSpec & TDD TutorialRSpec & TDD Tutorial
RSpec & TDD Tutorial
 
ALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborateALPHAhackathon: How to collaborate
ALPHAhackathon: How to collaborate
 
Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀Git 版本控制系統 -- 從微觀到宏觀
Git 版本控制系統 -- 從微觀到宏觀
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事從 Classes 到 Objects: 那些 OOP 教我的事
從 Classes 到 Objects: 那些 OOP 教我的事
 
Yet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom upYet another introduction to Git - from the bottom up
Yet another introduction to Git - from the bottom up
 
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
A brief introduction to Vagrant – 原來 VirtualBox 可以這樣玩
 
Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介Ruby 程式語言綜覽簡介
Ruby 程式語言綜覽簡介
 
A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0A brief introduction to SPDY - 邁向 HTTP/2.0
A brief introduction to SPDY - 邁向 HTTP/2.0
 
RubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & ClosingRubyConf Taiwan 2012 Opening & Closing
RubyConf Taiwan 2012 Opening & Closing
 
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
從 Scrum 到 Kanban: 為什麼 Scrum 不適合 Lean Startup
 
Git Tutorial 教學
Git Tutorial 教學Git Tutorial 教學
Git Tutorial 教學
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
 
RubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & ClosingRubyConf Taiwan 2011 Opening & Closing
RubyConf Taiwan 2011 Opening & Closing
 

Rails3 changesets

  • 1. Rails3 changesets ihower@gmail.com 2010/8/17
  • 2. About Me • a.k.a. ihower • http://ihower.tw • http://twitter.com/ihower • Rails Developer since 2006 • The Organizer of Ruby Taiwan Community • http://ruby.tw • http://rubyconf.tw
  • 3. Agenda • Bundler • ActiveRecord: New Query API • ActiveRecord: New Validation API • Views: XSS, Block Helper and JavaScript • I18n • New Routing API • New ActionMailer • Metal
  • 5. Gemfile # gem "rails", "3.0.0.rc" # require :require gem "sqlite3-ruby", :require => "sqlite3" # Git branch, tag ref gem 'authlogic', :git => 'git://github.com/odorcicd/authlogic.git', :branch => 'rails3' # gem "rails", :path => '/Users/ihower/github/rails' # Group group :test do gem "rspec-rails", ">= 2.0.0.beta.8" gem "webrat" end
  • 7. AR queries (1) method chaining # Rails 2 users = User.find(:all, :conditions => { :name => 'ihower' }, :limit => 10, :order => 'age') # Rails 3 users = User.where(:name => 'ihower').limit(20).order('age')
  • 8. AR queries (2) Unify finders, named_scope, with_scope to Relation # Rails 2 users = User users = users.some_named_scope if params[:some] sort = params[:sort] || "id" conditions = {} if params[:name] conditions = User.merge_conditions( conditions, { :name => params[:name] } ) end if params[:age] conditions = User.merge_conditions( conditions, { :age => params[:age] } ) end find_conditions = { :conditions => conditions, :order => "#{sort} #{dir}" } sort = params[:sort] || "id" users = users.find(:all, :conditions => conditions, :order => sort )
  • 9. AR queries (2) Unify finders, named_scope, with_scope to Relation # Rails 3 users = User users = users.some_scope if params[:some] users = users.where( :name => params[:name] ) if params[:name] users = users.where( :age => params[:age] ) if params[:age] users = users.order( params[:sort] || "id" )
  • 10. AR queries (3) Using class methods instead of scopes when you need lambda # Rails 3 class Product < ActiveRecord::Base scope :discontinued, where(:discontinued => true) scope :cheaper_than, lambda { |price| where("price < ?", price) } end # Rails 3, prefer this way more class Product < ActiveRecord::Base scope :discontinued, where(:discontinued => true) def self.cheaper_than(price) where("price < ?", price) end end
  • 12. AR validation (1) # Rails 2 class User < ActiveRecord::Base validates_presence_of :email validates_uniqueness_of :email validates_format_of :email, :with => /^[wd]+$/ :on => :create, :message => "is invalid" end # Rails 3 class User < ActiveRecord::Base validates :email, :presence => true, :uniqueness => true, :format => { :with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i } end http://asciicasts.com/episodes/211-validations-in-rails-3
  • 13. AR validation (2) custom validator # Rails 3 class User < ActiveRecord::Base validates :email, :presence => true, :uniqueness => true, :email_format => true end class EmailFormatValidator < ActiveModel::EachValidator def validate_each(object, attribute, value) unless value =~ /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i object.errors[attribute] << (options[:message] || "is not formatted properly") end end end
  • 15. Secure XSS Rails3 will automatically escape any string that does not originate from inside of Rails itself # Rails2 <%=h @person.title %> # Rails3 <%=@person.title %> # unescape string <%= @person.title.html_safe %> <%= raw @person.title %>
  • 16. Unobtrusive JavaScript # Rails 2 link_to_remote "Name", url_path # Rails 3 link_to "Name", url_path, :remote => true # Rails 2 remote_form_for @article do end # Rails 3 form_for @article, :remote => true do end
  • 17. You can change rails.js to jQuery version http://ihower.tw/blog/archives/3917
  • 18. consistent <%= %> # Rails 2 <% form_for @article do %> end <% content_for :sidebar do %> <% end %> # Rails 3 <%= form_for @article do %> end <%= content_for :sidebar do %> <% end %>
  • 19. consistent <%= %> (2) # Rails2 <% my_helper do %> blah <% end %> # Rails2 Helper def my_helper concat("header") yield concat("footer") end # or def my_helper(&block) tmp = with_output_buffer(&block) concat("header #{tmp} footer") end
  • 20. consistent <%= %> (3) # Rails3 <%= my_helper do %> blah <% end %> # Rails3 Helper def my_helper(&block) tmp = with_output_buffer(&block) "header #{tmp} footer" end
  • 22. {{ }} becomes to %{}
  • 24. Routes nice DSL # Rails 2 map.resources :people, :member => { :dashboard => :get, :resend => :post, :upload => :put } do |people| people.resource :avatra end # Rails 3 resources :people do resource :avatar member do get :dashboard post :resend put :upload end end
  • 26. ActionMailer # Rails 2 class UserMailer < ActionMailer::Base def signup(user) recipients user.email from 'ihower@gmail.com' body :name => user.name subject "Signup" end end UserMailer.deliver_registration_confirmation(@user)
  • 27. ActionMailer # Rails 3 class UserMailer < ActionMailer::Base default :from => "ihower@gmail.com" def signup(user) @name = user.name mail(:to => user.email, :subject => "Signup" ) end end UserMailer.registration_confirmation(@user).deliver
  • 29. Removing Metal • Use Rack middleware • Use Rack endpoint in the router • you can inherit ActionController::Metal to gain controller’s feature
  • 30. Yehuda’s benchmark rps 2900 Rack 2200 config.middleware.use YourMiddleware 2000 Rails Route 1900 ActionController::Metal 1070 ActionController::Base 825 ActionController::Base render :text 765 ActionController::Base render :template 375 ActionController::Base Template Layout