rails - DRY respond_to重复操作

kik*_*ito 14 controller ruby-on-rails dry

在我的一个rails控制器中,我必须响应几种类型的格式,所以我使用典型的respond_to链:

respond_to do |format|
  format.html   { ... }
  format.mobile { ... }
  format.jpg  { ... }
  format.xml  { ... }
  format.js   { ... }
end
Run Code Online (Sandbox Code Playgroud)

通常,{ ... }部件会以多种格式重复出现.在这种情况下保持DRY的最佳方法是什么?在一个场景中html,mobile并且xml有一个"重复"的动作,我想做这样的事情:

respond_to do |format|
  format[:html, :mobile, :xml] { ... }
  format.jpg  { ... }
  format.js   { ... }
end
Run Code Online (Sandbox Code Playgroud)

非常感谢.

小智 21

你试过format.any(:html,:mobile,:xml)吗?

示例(添加2011/9/14)

来自rails doc

响应还允许您使用any指定不同格式的公共块:

def index
  @people = Person.all

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

在上面的例子中,如果格式是xml,它将呈现:

render :xml => @people
Run Code Online (Sandbox Code Playgroud)

或者如果格式是json:

render :json => @people
Run Code Online (Sandbox Code Playgroud)


jon*_*nii 5

你能举例说明你所看到的重复吗?

你总是可以这样做:

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

protected 

def common_stuff
  ...
end
Run Code Online (Sandbox Code Playgroud)

我认为这样的事情可以被重构(我可能错了,因为我总是忘记如何将方法用作块:

[:html, :mobile, :xml].each { |f| format.send(:f, lambda{ common_stuff }) }
Run Code Online (Sandbox Code Playgroud)

话虽如此,我认为你对前者更好,因为它更明确.