rails - DRY respond_to with repeated actions

China☆狼群 提交于 2019-12-01 02:40:45
Eric Hu

Have you tried format.any(:html, :mobile, :xml)?

Example (added 2011/9/14)

From the rails doc

Respond to also allows you to specify a common block for different formats by using any:

def index
  @people = Person.all

  respond_to do |format|
    format.html
    format.any(:xml, :json) { render request.format.to_sym => @people }
  end
end

In the example above, if the format is xml, it will render:

render :xml => @people

Or if the format is json:

render :json => @people

Can you give an example of the repetition you're seeing?

You could always do something like this:

respond_to do |do|
  format.html { common_stuff }
  format.mobile { common_stuff }
  format.xml { common_stuff }
  ...
end

protected 

def common_stuff
  ...
end

I think something like that could be refactored to (I probably got this wrong as I always forget how to use a method as a block:

[:html, :mobile, :xml].each { |f| format.send(:f, lambda{ common_stuff }) }

Having said that, I think you're better off with the former as it's more explicit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!