mltsy
mltsy

Reputation: 7084

Explain the difference between ActionController#respond_to and ActionController::respond_to

I've read the documentation, and it confuses me every time, just because it doesn't answer some basic things. I realize the main purpose of the class method ::respond_to (which is normally used at the top of the controller) is for use in conjunction with respond_with. And the purpose of the instance method #respond_to (normally at the end of each action) is to provide different responses for different formats.

I also know that it's possible to consolidate the instance method version to look like the class method, but used inside an action, for conciseness, like this: respond_to(:html). The use case for this is another purpose of #respond_to, which is to refuse requests for unspecified formats. (I think it raises an UnspecifiedFormat exception)

Does the class method also have the same functionality? For instance, if I have a controller that only responds to html, if I just put respond_to(:html) at the top of the file, can I expect it to refuse requests for other formats? I've had problems with it doing that, so I don't know if I've been doing something wrong, or if it's just not supposed to work the same as the instance method in that respect.

Upvotes: 2

Views: 109

Answers (1)

mltsy
mltsy

Reputation: 7084

So I finally ran an experiment, and no, the class method respond_to does NOT refuse requests to unspecified formats like the instance method does. Kind of a confusing disparity, but there you have it. If you want to refuse requests for invalid formats (with a 406), you have to specify valid formats inside each action of each controller (using the instance method respond_to)

Upvotes: 1

Related Questions