rails - DRY response_to 重复动作 [英] rails - DRY respond_to with repeated actions
问题描述
在我的一个 rails 控制器中,我必须响应几种类型的格式,所以我使用典型的 respond_to
链:
In one of my rails controller, I must respond to several types of formats, so I use the typical respond_to
chain:
respond_to do |format|
format.html { ... }
format.mobile { ... }
format.jpg { ... }
format.xml { ... }
format.js { ... }
end
通常 { ... }
部分在几种格式中重复.在这种情况下保持干燥的最佳方法是什么?在 html
、mobile
和 xml
具有重复"操作的情况下,我想做这样的事情:>
Usually that the { ... }
part is repeated on several formats. What is the best way to stay DRY on this case? On an scenario in which html
, mobile
and xml
have a "repeated" action, I'd like to do something like this:
respond_to do |format|
format[:html, :mobile, :xml] { ... }
format.jpg { ... }
format.js { ... }
end
非常感谢.
推荐答案
你试过 format.any(:html, :mobile, :xml) 吗?
Have you tried format.any(:html, :mobile, :xml)?
示例(2011/9/14 添加)
来自 rails 文档
Respond to 还允许您使用 any 为不同的格式指定一个公共块:
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
在上面的例子中,如果格式是xml,则渲染:
In the example above, if the format is xml, it will render:
render :xml => @people
或者如果格式是json:
Or if the format is json:
render :json => @people
这篇关于rails - DRY response_to 重复动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!