首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby on Rails 2.0 新特性全覽:RESTful 路由、MultiView、安全強化、效能優化

     編輯:Java 相關知識

Rails 2.0 於 2007/12/7 發布,歷經近一年開發,帶來大量里程碑級特性。從 1.0 的測試框架、1.1 的 Migration/RJS、1.2 的 REST 支援,到 2.0 徹底重塑路由、視圖、安全、效能。本文彙整 DHH 官方發布文重點。

Action Pack:資源導向路由(RESTful Routing)

  • 斜線取代分號:/people/1;edit → /people/1/edit
  • 命名空間支援:後台管理路由分組
map.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 等命名路由
  • rake routes:列出所有命名路由
  • 預設 Controller 複數化:單一資源多處引用仍指向同一 Controller(如 AvatarsController)

Action Pack:MultiView(模板格式擴展)

新模板命名慣例:action.format.renderer

  • show.erb:所有格式預設 ERB
  • index.atom.builder:Builder 產出 Atom XML
  • edit.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

Action Pack:Record Identification(資源識別簡化)

直接傳 Model 物件產生路由:

redirect_to(person)           # → person_url(person)
link_to(person.name, person)  # → /people/1
form_for(person)              # 表單自動對應

Action Pack:HTTP Loving(深度 HTTP 整合)

  • HTTP Basic 認證:authenticate_or_request_with_http_basic 簡單跨 SSL API 驗證
  • JS/CSS 打包快取:javascript_include_tag(:all, :cache => true) 生產環境合併為 all.js,開發環境保持分離
  • 多域名靜態資源:ActionController::Base.asset_host = "assets%d.example.com" 自動分發至 assets1/2/3,瀏覽器並行下載提速

Action Pack:Security(安全強化)

  • CSRF 內建防護:表單/AJAX 自動嵌入 Token,新專案預設開啟,舊專案 protect_from_forgery 啟用
  • XSS 白名單過濾:TextHelper#sanitize 從黑名單改白名單,自動獲得更強防護
  • HTTP Only Cookies:支援現代瀏覽器防 XSS 竊取 Cookie

Action Pack:Exception Handling(統一異常處理)

class PostsController < ApplicationController
  rescue_from User::NotAuthorized, :with => :deny_access
  protected
  def deny_access; ...; end
end

Action Pack:Cookie Store Session(預設 Session 機制變更)

  • Session 以 Ruby Hash 序列化存於 Client Cookie,無需 Server 儲存
  • 優點:快、免維護、不佔 /tmp、不會因 session 檔案過多 crash
  • 缺點:不可加密、用戶可見、不適合存敏感資料(如權限旗標)
  • 最佳實踐:僅存 user_id、flash 等最小資料

Action Pack:Request Profiler(效能分析)

$ 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 報告,每步耗時一目了然

ActiveRecord:效能與易用性

  • 查詢快取:同一 Request 內自動快取相同 SQL 結果,緩解 N+1 問題
  • Fixtures 效能提升 50-100%
  • Sexy Migrations:新語法更簡潔
# 舊
t.column "first_name", :string, :null => false
# 新
t.string :first_name, :last_name, :null => false
t.timestamps  # 自動建立 created_at, updated_at
  • Foxy Fixtures:以名稱而非 ID 關聯 Fixtures
# sellers.yml
shopify:
  name: Shopify

# products.yml
pimp_cup:
  seller: shopify  # 直接引用名稱
  name: Pimp cup
  • XML 反序列化 + JSON 序列化:Person.new.from_xml(xml)、person.to_json(:include => :posts)
  • 移除 acts_as_* 至 Plugin:script/plugin install acts_as_list
  • 商業資料庫驅動外移至 Gem:activerecord-oracle-adapter 等,Rails 核心僅含 MySQL/SQLite/PostgreSQL
  • with_scope 僅建議用於 Model:Controller/Filter 中需用 .send(:with_scope)

ActiveResource 取代 ActionWebService

  • REST 勝過 SOAP,ActionWebService 移出核心(Gem 保留)
  • ActiveResource 納入核心,API 與 ActiveRecord 相似,針對 RESTful 資源

ActiveSupport、Action Mailer、Debugger、環境整理

  • ActiveSupport:新增 Array#rand、Hash#except、Date 擴充、assert_difference
  • Action Mailer:可註冊替代樣板引擎、assert_emails 測試郵件發送數
  • Debugger 回歸:gem install ruby-debug,代碼插 debugger,script/server -u 啟動,真單步除錯
  • config/initializers/:啟動設定模組化,environment.rb 瘦身
  • Plugin 載入順序簡化:config.plugins = [:acts_as_list, :all]

升級指南

  1. 先升級至 Rails 1.2.6,確認無棄用警告
  2. 再升級至 2.0
  3. 若用分頁,安裝 classic_pagination plugin
  4. 若用 Oracle,安裝 activerecord-oracle-adapter gem

總結

Rails 2.0 確立了「RESTful、安全、效能、開發體驗」四大支柱。路由與視圖的 MultiView 機制、內建 CSRF/XSS 防護、Cookie Session、Request Profiler、Sexy Migrations、Foxy Fixtures、ActiveResource 納入核心,皆為現代 Web 開發奠基。升級路徑清晰,生態系模組化(Plugin/Gem)更健康。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved