RoR - Two respond_to formats using same block?
Is there something like:
respond_to do |format|
format.html || format.xml do
#big chunk of code
end
end
I would li开发者_JAVA技巧ke to do that for DRY's sake.
Respond_to actually allows you to specify your common block for different formats by using any:
format.any(:js, :json) { #your_block }
You can use a format like this:
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
Which would achieve what you are looking for, if you have a situation that is more complex let me know. See this article on the respond_with method for more help.
when you
respond_to do |format|
format.html do
#block
end
format.xml do
#block
end
end
or you
respond_to do |format|
format.html { #block }
format.xml { #block }
end
you are taking advantage of ruby blocks, which are evaluated as Procs. Therefore you could do
respond_to do |format|
bcoc = Proc.new do
# your big chunk of code here
end
format.html bcoc
format.xml bcoc
end
but perhaps you could move some of that logic into your data structure?
精彩评论