Cleaner RESTful Controllers with respond_with

REST is a first-class citizen in the Rails world, though most of the hard work is done at the routing level. The controller stack has some niceties revolving around mime type handling with the respond_to facility but, to date, there’s not been a lot built into actionpack to handle the serving of resources. The addition of respond_with (and this follow-up) takes one step towards more robust RESTful support with an easy way to specify how resources are delivered. Here’s how it works:

Basic Usage

In your controller you can specify what resource formats are supported with the class method respond_*to*. Then, within your individual actions, you tell the controller the resource or resources to be delivered using respond_*with*:

This will match each supported format with an appropriate response. For instance, if the request is for /users.xml then the controller will look for a /users/index.xml.erb view template to render. If such a view template doesn’t exist then it tries to directly render the resource in the :xml format by invoking to_xml (if it exists). Lastly, if respond_with was invoked with a :location option the request will be redirected to that location (as in the case of the create action in the above example).

So here’s the equivalent implementation without the use of respond_with (assuming no index view templates):

You can see how much boilerplate response handling is now handled for you especially if it’s multiplied over the other default actions. You can pass in :status and :head options to respond_with as well if you need to send these headers back on resources rendered directly (i.e. via to_xml):

Per-Action Overriding

It’s also possible to override standard resource handling by passing in a block to respond_with specifying which formats to override for that action:

classUsersController<ApplicationController::Baserespond_to:html,:xml,:json# Override html format since we want to redirect to a different page,# not just serve back the new resourcedefcreate@user=User.create(params[:user])respond_with(@user)do|format|format.html{redirect_tousers_path}endendend

:except And :only Options

You can also pass in :except and :only options to only support formats for specific actions (as you do with before_filter):

So all in all this is a small, but meaningful, step towards robust controller-level REST support. I should point out that the contributor of this patch is José Valim who has authored the very robust inherited_resources framework that already has support for respond_with-like functionality and many more goodies. If you’re on the search for a solid RESTful controller framework to accompany Rails’ native RESTful routing support I would suggest you take a look at his fine work.