Rails 2.0 於 2007/12/7 發布,歷經近一年開發,帶來大量里程碑級特性。從 1.0 的測試框架、1.1 的 Migration/RJS、1.2 的 REST 支援,到 2.0 徹底重塑路由、視圖、安全、效能。本文彙整 DHH 官方發布文重點。
/people/1;edit → /people/1/editmap.namespace(:admin) do |admin|
admin.resources :products,
:collection => { :inventory => :get },
:member => { :duplicate => :post },
:has_many => [ :tags, :images, :variants ]
end
# 產生 inventory_admin_products_url, admin_product_tags_url 等命名路由
AvatarsController)新模板命名慣例:action.format.renderer
show.erb:所有格式預設 ERBindex.atom.builder:Builder 產出 Atom XMLedit.iphone.haml:HAML 產出 iPhone 版面自訂 MIME 類型:
# config/initializers/mime_types.rb
Mime.register_alias "text/html", :iphone
class ApplicationController < ActionController::Base
before_filter :adjust_format_for_iphone
private
def adjust_format_for_iphone
if request.env["HTTP_USER_AGENT"] =~ /(iPhone|iPod)/
request.format = :iphone
end
end
end
直接傳 Model 物件產生路由:
redirect_to(person) # → person_url(person)
link_to(person.name, person) # → /people/1
form_for(person) # 表單自動對應
authenticate_or_request_with_http_basic 簡單跨 SSL API 驗證javascript_include_tag(:all, :cache => true) 生產環境合併為 all.js,開發環境保持分離ActionController::Base.asset_host = "assets%d.example.com" 自動分發至 assets1/2/3,瀏覽器並行下載提速protect_from_forgery 啟用TextHelper#sanitize 從黑名單改白名單,自動獲得更強防護class PostsController < ApplicationController
rescue_from User::NotAuthorized, :with => :deny_access
protected
def deny_access; ...; end
end
user_id、flash 等最小資料$ cat login_session.rb
get_with_redirect '/'
post_with_redirect '/sessions', :username => 'john', :password => 'doe'
$ ./script/performance/request -n 10 login_session.rb
# 產出詳細 HTML/Text 報告,每步耗時一目了然
# 舊
t.column "first_name", :string, :null => false
# 新
t.string :first_name, :last_name, :null => false
t.timestamps # 自動建立 created_at, updated_at
# sellers.yml
shopify:
name: Shopify
# products.yml
pimp_cup:
seller: shopify # 直接引用名稱
name: Pimp cup
Person.new.from_xml(xml)、person.to_json(:include => :posts)script/plugin install acts_as_listactiverecord-oracle-adapter 等,Rails 核心僅含 MySQL/SQLite/PostgreSQL.send(:with_scope)Array#rand、Hash#except、Date 擴充、assert_differenceassert_emails 測試郵件發送數gem install ruby-debug,代碼插 debugger,script/server -u 啟動,真單步除錯environment.rb 瘦身config.plugins = [:acts_as_list, :all]classic_pagination pluginactiverecord-oracle-adapter gemRails 2.0 確立了「RESTful、安全、效能、開發體驗」四大支柱。路由與視圖的 MultiView 機制、內建 CSRF/XSS 防護、Cookie Session、Request Profiler、Sexy Migrations、Foxy Fixtures、ActiveResource 納入核心,皆為現代 Web 開發奠基。升級路徑清晰,生態系模組化(Plugin/Gem)更健康。