1 基礎設施
Rails 2.2 是基礎設施的一個重要版本,它使 Rails 保持與世界其他地方的聯絡。
1.1 國際化
Rails 2.2 提供了一個簡單的國際化系統(或 i18n,對於那些厭倦了打字的人)。
- 主要貢獻者:Rails i18 團隊
- 更多資訊 :
1.2 與 Ruby 1.9 和 JRuby 的相容性
除了執行緒安全之外,還做了很多工作來使 Rails 能夠很好地與 JRuby 和即將推出的 Ruby 1.9 配合使用。由於 Ruby 1.9 是一個不斷變化的目標,在邊緣 Ruby 上執行邊緣 Rails 仍然是一個命中註定的命題,但 Rails 已準備好在 Ruby 1.9 釋出時過渡到 Ruby 1.9。
2 文件
Rails 的內部文件,以程式碼註釋的形式,在很多地方都得到了改進。此外,Ruby on Rails 指南 專案是有關主要 Rails 元件資訊的權威來源。在第一個正式版本中,指南頁面包括:
- Rails 入門
- Rails 資料庫Migrations
- Active Record Associations
- Active Record 查詢介面
- Rails 中的佈局和渲染
- Action View 表單Helpers
- Rails 從外向內路由
- Action Controller 概覽
- Rails 快取
- 測試 Rails 應用程式指南
- 保護 Rails 應用程式
- 除錯 Rails 應用程式
- 建立Rails外掛的基礎
總而言之,這些指南為初級和中級 Rails 開發人員提供了數萬字的指導。
如果您想在本地生成這些指南,請在您的應用程式中:
$ rake doc:guides
這會將指南放在 Rails.root/doc/guides
中,你可以透過在你喜歡的瀏覽器中開啟 Rails.root/doc/guides/index.html
立即開始衝浪。
- 主要貢獻來自 Xavier Noria 和 Hongli Lai。
- 更多資訊:
3 更好地與 HTTP 整合:開箱即用的 ETag 支援
支援 HTTP 標頭中的 ETag 和上次修改時間戳意味著 Rails 現在可以在收到對最近未修改的資源的請求時發回空回應。這允許您檢查是否需要傳送回應。
class ArticlesController < ApplicationController
def show_with_respond_to_block
@article = Article.find(params[:id])
# If the request sends headers that differs from the options provided to stale?, then
# the request is indeed stale and the respond_to block is triggered (and the options
# to the stale? call is set on the response).
#
# If the request headers match, then the request is fresh and the respond_to block is
# not triggered. Instead, the default render will occur, which will check the last-modified
# and etag headers and conclude that it only needs to send a "304 Not Modified" instead
# of rendering the template.
if stale?(:last_modified => @article.published_at.utc, :etag => @article)
respond_to do |wants|
# normal response processing
end
end
end
def show_with_implied_render
@article = Article.find(params[:id])
# Sets the response headers and checks them against the request, if the request is stale
# (i.e. no match of either etag or last-modified), then the default render of the template happens.
# If the request is fresh, then the default render will return a "304 Not Modified"
# instead of rendering the template.
fresh_when(:last_modified => @article.published_at.utc, :etag => @article)
end
end
4 執行緒安全
為使 Rails 執行緒安全所做的工作正在 Rails 2.2 中推出。根據您的 Web 伺服器基礎架構,這意味著您可以使用記憶體中更少的 Rails 副本處理更多請求,從而提高伺服器效能並提高多核利用率。
要在應用程式的生產模式下啟用多執行緒排程,請在“config/environments/production.rb”中新增以下行:
config.threadsafe!
5 Active Record
這裡有兩個重要的補充要討論:事務遷移和池化資料庫事務。連線表條件還有一個新的(更乾淨的)語法,以及一些較小的改進。
5.1 交易Migrations
從歷史上看,多步 Rails 遷移一直是麻煩的根源。如果遷移過程中出現問題,錯誤之前的所有內容都會更改資料庫,錯誤之後的所有內容都不會應用。此外,遷移版本被儲存為已執行,這意味著在修復問題後不能簡單地透過 rake db:migrate:redo
重新執行它。事務性遷移透過將遷移步驟包裝在 DDL 事務中來改變這一點,因此如果其中任何一個失敗,整個遷移將被撤消。在 Rails 2.2 中,PostgreSQL 開箱即用地支援事務遷移。該程式碼將來可以擴充套件到其他資料庫型別——IBM 已經對其進行了擴充套件以支援 DB2 介面卡。
- 主要貢獻者:Adam Wiggins
- 更多資訊:
5.2 連線池
連線池讓 Rails 將資料庫請求分佈在將增長到最大大小的資料庫連線池中(預設為 5,但您可以向您的 database.yml
新增一個 pool
鍵來調整它)。這有助於消除支援許多併發使用者的應用程式中的瓶頸。還有一個 wait_timeout
,預設為 5 秒後放棄。 ActiveRecord::Base.connection_pool
可讓您在需要時直接訪問池。
development:
adapter: mysql
username: root
database: sample_development
pool: 10
wait_timeout: 10
- 主要貢獻者:Nick Sieger
- 更多資訊:
5.3 連線表條件的雜湊
您現在可以使用雜湊在連線表上指定條件。如果您需要跨複雜連線進行查詢,這將有很大幫助。
class Photo < ActiveRecord::Base
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :photos
end
# Get all products with copyright-free photos:
Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }})
- 更多資訊:
- [Edge Rails 的新功能:輕鬆連線表條件](http://archives.ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-狀況)
5.4 新動態查詢器
Active Record 的動態查詢器系列中添加了兩組新方法。
5.4.1 find_last_by_attribute
find_last_by_attribute
方法等價於 Model.last(:conditions => {:attribute => value})
# Get the last user who signed up from London
User.find_last_by_city('London')
- 主要貢獻者:Emilio Tagua
5.4.2 find_by_attribute!
新的爆炸! find_by_attribute!
的版本等價於 Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound
如果找不到匹配的記錄,則此方法不會返回 nil
,而是在找不到匹配項時引發異常。
# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet!
User.find_by_name!('Moby')
- 主要貢獻者:Josh Susser
5.5 Associations 尊重私有/受保護範圍
Active Record 關聯代理現在尊重代理物件上的方法範圍。以前(給定 User has_one :account)@user.account.private_method
會呼叫關聯 Account 物件上的私有方法。這在 Rails 2.2 中失敗了;如果你需要這個功能,你應該使用@user.account.send(:private_method)
(或者將方法設為public而不是private或protected)。請注意,如果您覆蓋 method_missing
,您還應該覆蓋 respond_to
以匹配行為,以便關聯正常執行。
- 主要貢獻者:Adam Milligan
- 更多資訊:
- [Rails 2.2 更改:Association 代理上的私有方法是私有的](http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-私人的/)
5.6 其他Active Record 更改
-
rake db:migrate:redo
現在接受一個可選的 VERSION 來針對特定的重做遷移 - 設定
config.active_record.timestamped_migrations = false
以使用數字字首而不是 UTC 時間戳進行遷移。 - 計數器快取列(對於用
:counter_cache => true
宣告的關聯)不再需要初始化為零。 -
ActiveRecord::Base.human_name
用於模型名稱的國際化感知人性化翻譯
6 Action Controller
在控制器方面,有一些更改將有助於整理您的路線。路由引擎也有一些內部變化,以降低複雜應用程式的記憶體使用量。
6.1 淺層路由巢狀
淺層路由巢狀為眾所周知的使用深層巢狀資源的困難提供瞭解決方案。使用淺巢狀,您只需提供足夠的資訊來唯一標識您要使用的資源。
map.resources :publishers, :shallow => true do |publisher|
publisher.resources :magazines do |magazine|
magazine.resources :photos
end
end
這將能夠識別(除其他外)這些路線:
/publishers/1 ==> publisher_path(1)
/publishers/1/magazines ==> publisher_magazines_path(1)
/magazines/2 ==> magazine_path(2)
/magazines/2/photos ==> magazines_photos_path(2)
/photos/3 ==> photo_path(3)
- 主要貢獻者:S.布倫特福克納
- 更多資訊:
6.2 成員或集合路由的方法陣列
您現在可以為新成員或集合路由提供一系列方法。這消除了在需要處理多個動詞時必須將路由定義為接受任何動詞的煩惱。對於 Rails 2.2,這是一個合法的路由宣告:
map.resources :photos, :collection => { :search => [:get, :post] }
- 主要貢獻者:Brennan Dunn
6.3 具有特定 Action 的資源
預設情況下,當您使用 map.resources
建立路由時,Rails 會為七個預設操作(索引、顯示、建立、新建、編輯、更新和銷燬)生成路由。但是這些路由中的每一個都會佔用應用程式中的記憶體,並導致 Rails 生成額外的路由邏輯。現在你可以使用 :only
和 :except
選項來微調 Rails 將為資源生成的路由。您可以提供單個操作、一組操作或特殊的 :all
或 :none
選項。這些選項由巢狀資源繼承。
map.resources :photos, :only => [:index, :show]
map.resources :products, :except => :destroy
- 主要貢獻者:Tom Stuart
6.4 其他 Action Controller 更改
- 您現在可以輕鬆地顯示自定義錯誤頁面 路由請求時引發的異常。
- HTTP Accept 標頭現在預設禁用。您應該更喜歡使用格式化的 URL(例如
/customers/1.xml
)來指示您想要的格式。如果您需要 Accept 標頭,您可以使用config.action_controller.use_accept_header = true
重新開啟它們。 - 基準資料現在以毫秒為單位報告,而不是幾分之一秒
- Rails 現在支援僅 HTTP cookie(並將它們用於會話),這有助於減輕較新瀏覽器中的一些跨站點指令碼風險。
-
redirect_to
現在完全支援 URI 方案(例如,您可以重定向到 svn`ssh: URI)。 -
render
現在支援:js
選項以使用正確的 mime 型別渲染普通的 JavaScript。 - 已加強請求偽造保護,僅適用於 HTML 格式的內容請求。
- 如果傳遞的引數為零,多型 URL 的行為會更明智。例如,使用 nil 日期呼叫
polymorphic_path([@project, @date, @area])
將為您提供project_area_path
。
7 Action View
-
javascript_include_tag
和stylesheet_link_tag
支援一個新的:recursive
選項與:all
一起使用,這樣你就可以用一行程式碼載入整個檔案樹。 - 包含的 Prototype JavaScript 庫已升級到 1.6.0.3 版。
-
RJS#page.reload
透過 JavaScript 重新載入瀏覽器的當前位置 -
atom_feed
助手現在採用:instruct
選項,讓您插入 XML 處理指令。
8 Action 郵寄者
Action 郵件程式現在支援郵件程式佈局。透過提供適當命名的佈局,您可以使您的 HTML 電子郵件與瀏覽器中的檢視一樣漂亮 - 例如,CustomerMailer
類期望使用 layouts/customer_mailer.html.erb
。
- 更多資訊:
Action Mailer 現在透過自動開啟 STARTTLS 為 GMail 的 SMTP 伺服器提供內建支援。這需要安裝 Ruby 1.8.7。
9 Active Support
Active Support 現在為 Rails 應用程式提供內建記憶、each_with_object
方法、對委託的字首支援以及各種其他新的實用方法。
9.1 記憶
Memoization 是一種初始化方法,然後將其值隱藏起來以備重複使用的模式。您可能已經在自己的應用程式中使用過這種模式:
def full_name
@full_name ||= "#{first_name} #{last_name}"
end
Memoization 可以讓你以宣告的方式處理這個任務:
extend ActiveSupport::Memoizable
def full_name
"#{first_name} #{last_name}"
end
memoize :full_name
memoization 的其他功能包括 unmemoize
、unmemoize_all
和 memoize_all
以開啟或關閉備忘錄。
- 主要貢獻者:Josh Peek
- 更多資訊:
9.2 each_with_object
each_with_object
方法使用從 Ruby 1.9 向後移植的方法提供了 inject
的替代方法。它遍歷一個集合,將當前元素和備忘錄傳遞到塊中。
%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } # => {'foo' => 'FOO', 'bar' => 'BAR'}
主要貢獻者:Adam Keys
9.3 帶字首的委託
如果您將行為從一個類委託給另一個類,您現在可以指定將用於標識委託方法的字首。例如:
class Vendor < ActiveRecord::Base
has_one :account
delegate :email, :password, :to => :account, :prefix => true
end
這將產生委託方法 vendor#account_email
和 vendor#account_password
。您還可以指定自定義字首:
class Vendor < ActiveRecord::Base
has_one :account
delegate :email, :password, :to => :account, :prefix => :owner
end
This will produce delegated methods vendor#owner_email
and vendor#owner_password
.
Lead Contributor: Daniel Schierbeck
9.4 Other Active Support Changes
- Extensive updates to
ActiveSupport::Multibyte
, including Ruby 1.9 compatibility fixes. - The addition of
ActiveSupport::Rescuable
allows any class to mix in therescue_from
syntax. -
past?
,today?
andfuture?
forDate
andTime
classes to facilitate date/time comparisons. -
Array#second
throughArray#fifth
as aliases forArray#[1]
throughArray#[4]
-
Enumerable#many?
to encapsulatecollection.size > 1
-
Inflector#parameterize
produces a URL-ready version of its input, for use into_param
. -
Time#advance
recognizes fractional days and weeks, so you can do1.7.weeks.ago
,1.5.hours.since
, and so on. - The included TzInfo library has been upgraded to version 0.3.12.
回饋
我們鼓勵您幫助提高本指南的品質。
如果您發現任何拼寫錯誤或資訊錯誤,請提供回饋。 要開始回饋,您可以閱讀我們的 回饋 部分。
您還可能會發現不完整的內容或不是最新的內容。 請務必為 main 新增任何遺漏的文件。假設是 非穩定版指南(edge guides) 請先驗證問題是否已經在主分支上解決。 請前往 Ruby on Rails 指南寫作準則 查看寫作風格和慣例。
如果由於某種原因您發現要修復的內容但無法自行修補,請您 提出 issue。
關於 Ruby on Rails 的任何類型的討論歡迎提供任何文件至 rubyonrails-docs 討論區。