0
respond_with
接受一些參數,例如, respond_with(@resource, methods: [:method])
這些選項應該用在每個動作中。因此,不用手動將其放入每種方法中,是否有可能爲該控制器設置一些默認選項?Rails 3.2 respond_with
respond_with
接受一些參數,例如, respond_with(@resource, methods: [:method])
這些選項應該用在每個動作中。因此,不用手動將其放入每種方法中,是否有可能爲該控制器設置一些默認選項?Rails 3.2 respond_with
這種簡單且可定製的方法是通過創建一個包裝responds_with的新響應方法。
例如:
class ResourcesController < ApplicationController
def index
@resources = Resource.all
custom_respond_with @resources
end
private
def custom_respond_with(data, options={})
options.reverse_merge!({
# Put your default options here
:methods => [ :method ],
:callback => params[:callback]
})
respond_with data, options
end
end
你可以,當然,也覆蓋respond_with完全,不過,我覺得如果你改變了方法的名稱,它是在代碼更加清晰。它也將允許您在大多數操作中使用custom_respond_with,但如果需要,還可以使用一個或兩個標準respond_with。
更進一步,如果將custom_respond_with方法移動到ApplicationController,則可以根據需要在所有控制器中使用它。
如果你想在每個控制器的基礎上指定不同的默認選項,你可以這樣做很容易:
class ResourcesController < ApplicationController
def index
custom_respond_with Resource.all
end
private
def custom_respond_options
{ :methods => [ :method ] }
end
end
class ApplicationController < ActionController::Base
protected
def default_custom_respond_options
{}
end
def custom_respond_with(data, options={})
options.reverse_merge! default_custom_respond_options
respond_with data, options
end
end