Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always use responds_to?

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?

like image 515
tfwright Avatar asked Jan 22 '10 23:01

tfwright


People also ask

What does Respond_to do in Rails?

A respond_to shortcut it works the same way as writing the full respond_to block in index . It's a short way to tell Rails about all the formats your action knows about. And if different actions support different formats, this is a good way to handle those differences without much code.

What is Respond_to in Ruby?

respond_to is a Rails method for responding to particular request types.


1 Answers

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"

like image 106
Ben Avatar answered Sep 28 '22 05:09

Ben