rails - DRY respond_to重复操作 [英] rails - DRY respond_to with repeated actions

查看:119
本文介绍了rails - DRY respond_to重复操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个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

通常< $ c> {...} 部分在几种格式上重复。在这种情况下保持干燥的最好办法是什么?在 html mobile xml 的情况下a重复动作,我想这样做:

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)?

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

在上面的示例中,是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 respond_to重复操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆