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 takes one step towards more robust RESTful support with an easy way to specify how resources are delivered. Here’s how it works:
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. So here’s the equivalent index action without the use of respond_with (assuming no index.xml.erb or index.json.erb views):
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 options to respond_with as well if you need to send headers back on resources rendered directly (i.e. via to_xml):
It’s also possible to override standard resource handling by passing in a block to respond_with specifying which formats to override:
12345678910111213
classUsersController < ApplicationController::Base respond_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_to users_path }endendend
If you’re still want to use respond_to within your individual actions this update has also bundled the :any resource format that can be used as a wildcard match against any unspecified formats:
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.