Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 822
miligraf Avatar asked Aug 23 '11 05:08

miligraf


3 Answers

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

format.any(:js, :json) { #your_block }
like image 82
Tom Chinery Avatar answered Nov 17 '22 08:11

Tom Chinery


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.

like image 21
Devin M Avatar answered Nov 17 '22 06:11

Devin M


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?

like image 1
Alec Wenzowski Avatar answered Nov 17 '22 08:11

Alec Wenzowski