miligraf
miligraf

Reputation: 1082

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 like to do that for DRY's sake.

Upvotes: 18

Views: 4944

Answers (3)

Tom Chinery
Tom Chinery

Reputation: 621

Respond_to actually allows you to specify your common block for different formats by using any:

format.any(:js, :json) { #your_block }

Upvotes: 48

Alec Wenzowski
Alec Wenzowski

Reputation: 3918

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?

Upvotes: 1

Devin M
Devin M

Reputation: 9752

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.

Upvotes: 4

Related Questions