Routing
Concerns
允許您宣告常見路由,可供其他資源和路由重複使用。
concern :commentable do
resources :comments
end
concern :image_attachable do
resources :images, only: :index
end
這些 concern 應用於 Resources
路由
resources :messages, concerns: [:commentable, :image_attachable]
或範疇或名稱空間
namespace :posts do
concerns :commentable
end
方法
執行個體公開方法
concern(name, callable = nil, &block) 連結
定義路由 concern 並使用一個名稱。
Concerns
可使用區塊內嵌定義,或透過將該物件傳遞為第二個參數,交由另一個物件處理。
若有提供 concern 物件,該物件應回應 call
,其將會收到兩個參數
* The current mapper
* A hash of options which the concern object may use
也可以使用 concern 定義區塊內接受區塊參數,如此將會限制特定資源上可用的動作,傳遞標準資源選項以透過 concern 傳遞
concern :commentable do |options|
resources :comments, options
end
resources :posts, concerns: :commentable
resources :archived_posts do
# Don't allow comments on archived posts
concerns :commentable, only: [:index, :show]
end
或者,透過使用可呼叫物件,您能夠針對應用程式實作更特定功能,該功能在路徑檔案內會不適當。
# purchasable.rb
class Purchasable
def initialize(defaults = {})
@defaults = defaults
end
def call(mapper, options = {})
options = @defaults.merge(options)
mapper.resources :purchases
mapper.resources :receipts
mapper.resources :returns if options[:returnable]
end
end
# routes.rb
concern :purchasable, Purchasable.new(returnable: true)
resources :toys, concerns: :purchasable
resources :electronics, concerns: :purchasable
resources :pets do
concerns :purchasable, returnable: false
end
任何路由輔助工具皆可使用於 concern 內部。如果使用可呼叫工具,則可從傳遞至 call
的 Mapper
存取。