respond_with
接受一些参数,例如这些respond_with(@resource, methods: [:method])
选项应该在每个动作中使用。因此,与其手动将其放入每个方法中,是否有可能仅为此控制器设置一些默认选项?
问问题
267 次
1 回答
1
实现这一点的简单且可定制的方法是创建一个包装response_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
于 2012-09-28T23:35:57.087 回答