繁体   English   中英

Rails 3.2 response_with

[英]Rails 3.2 respond_with

所述respond_with接受一些参数,例如respond_with(@resource, methods: [:method])这些选项应当在每一个动作中使用。 因此,除了手动将其放入每种方法之外,是否有可能仅为此控制器设置一些默认选项?

一种简单且可自定义的方法是通过创建一个包装responses_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

当然,您也可以完全覆盖response_with,但是,如果您更改方法的名称,我发现它在代码中会更加清晰。 它还允许您在大多数操作中使用custom_respond_with,但在必要时在一个或两个中使用标准response_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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM