Datasheet
Chapter 1: Building Resources
12
When the respond_to method is called, the outer block is invoked. Each format method is called, and
does nothing unless the format method name matches the type of the request. (Metaprogramming fans
should note that this is elegantly implemented using
method_missing .) If the types match, then
behavior associated with that type is invoked — either the block if one is explicitly passed or the default
behavior if not.
The convention is to have nothing in your respond_to block except for the format calls, and nothing in
the format calling blocks except the actual rendering call being made. This goes along with the general
idea in Rails design that the controller should be as thin as possible, and that complex data processing
should be handled in the model object.
The
respond_to method adds a lot of flexibility to your Rails controller — adding XML data serialization
or RSS feeds is nearly trivial. The syntax, I think, may still have some tweaking ahead of it — I ’ m not sure
there ’ s a lot of love for the way default behaviors are specified, and if the rendering is complex, the nested
blocks can become hard to read.
Rails defines eight formats for you:
atom , html , ics , js , rss , text , xml , and yaml . Just to be clear on
this,
html is used for ordinary browser output, atom and rss should be used for feeds, xml and yaml
are used for object syndication,
ics is the standard iCalendar format for calendar data, text is often
used for simple serialization, and
js is used either to serialize data via the JSON format or as the target
of an Ajax call that would trigger JavaScript.
Adding your own formats is simple, assuming that the format has a MIME type. Suppose you wanted to
allow a URL like
/recipes.png to return some kind of graphical display of your recipe list. All you
need to do is go into the
config/environment.rb file and add the following line:
Mime::Type.register “image.png”, :png
Now any respond_to block in your application will enable you to use format.png as a method.
Show
The default show method is nearly identical to the index method, except that it only takes a single recipe
from the database, and renders the
show.html.erb file.
# GET /recipes/1
# GET /recipes/1.xml
def show
@recipe = Recipe.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml = > @recipe }
end
end
The render :xml = > @recipe method call creates an XML representation of the data object by making
all of the attributes of the data object into subordinate tags of the XML (see Chapter 9 for more details).
c01.indd 12c01.indd 12 1/30/08 4:02:24 PM1/30/08 4:02:24 PM