Is there something like:
respond_to do |format|
format.html || format.xml do
#big chunk of code
end
end
I would like 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With