views:

94

answers:

3

Until now I have always specified the format of the response for actions using a responds_to block, like so:

responds_to do |format|
  format.js { render :json => @record }
end

Recently I realized that if you only support one format (as in the above example), you don't really need that block. Is it best practice to leave it in, or remove it?

A: 

I'm not really sure if this is best practice or not, but usually what I like to do is to leave the routes open to respond_to (i.e. by appending .:format to the end), but only use it in the controllers when it's necessary.

Example:

routes.rb

map.connect :controller/:action/:id.:format

model_controller.rb

# Return a collection of model objects
def action_with_multiple_responses
  @models = Model.all

  respond_to do |format|
    format.html #=> action_with_multiple_responses.html
    format.xml  { render :xml => @models }
  end
end

# Return the first model object
def action_with_one_response
  @model = Model.first
end

That way, you aren't cluttering up your action_with_one_response method with an unnecessary block, but you also have set yourself up quite nicely if you want to someday return your object in xml, json, etc.

jerhinesmith
I believe :format is added by default.
vise
It is if you use `map.resources`, but I don't believe it is if you just use `map.connect` -- at least, that has been my experience (unless I'm doing something else wrong).
jerhinesmith
Yeah, map.resources will set a raft of RESTful routes attached to the controller specified. Connect sets up a specific path in the format specified.
Toby Hede
A: 

I would say not to use respond_to unless you have multiple response types.

It is simply extra code to understand and for your app to process and handle:

render :json => @record

Is much more concise than:

responds_to do |format|
  format.js { render :json => @record }
end
Toby Hede
+1  A: 

I'm going to differ with existing answers--I like to have a responds_to block for all of my actions. I find that, while slightly more verbose, it more clearly self-documents the action. It also makes it easy to support additional formats in the future. Edit: another advantage is it acts as a gatekeeper. Any format not declared in the block is automatically served a "406 Not Acceptable"

Ben
Hadn't thought of the gatekeeper idea, nice one.
Toby Hede
is that the case, that in my example above a request (for html, without the .js) would get a 406 and just just the record json without the correct header? if so that's huge...
floyd
Yes, with your `responds_to` block above, a request for .xml, .html etc should return `406 Not Acceptable`.
Ben