RoR - 使用相同块的两种respond_to格式?

时间:2011-08-23 05:31:56

标签: ruby-on-rails

是否有类似的东西:

respond_to do |format|

  format.html || format.xml do
    #big chunk of code
  end

end

我想为了DRY而这样做。

3 个答案:

答案 0 :(得分:36)

Respond_to实际上允许您使用any

为不同格式指定公共块
format.any(:js, :json) { #your_block }

答案 1 :(得分:4)

您可以使用以下格式:

class PeopleController < ApplicationController
  respond_to :html, :xml, :js

  def index
    @people = Person.find(:all)
    respond_with(@people) do |format|
        format.html
        format.xml
        format.js { @people.custom_code_here }
    end
  end
end

如果您的情况更复杂,请告诉我,哪个会实现您的目标。有关更多帮助,请参阅此article on the respond_with方法。

答案 2 :(得分:1)

当你

respond_to do |format|
  format.html do
    #block
  end
  format.xml do
    #block
  end
end

或者你

respond_to do |format|
  format.html { #block }
  format.xml { #block }
end

您正在利用ruby blocks,其被评估为Procs。因此你可以做到

respond_to do |format|
  bcoc = Proc.new do
    # your big chunk of code here
  end
  format.html bcoc
  format.xml bcoc
end

但也许您可以将一些逻辑移到数据结构中?