Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

218 | Chapter 7: REST, Resources, and Web Services


The respond_tomethod yields a responder (an instance of ActionController::
MimeResponds::Responder, usually calledformat), which can respond to various con-
tent type methods in order to send different content based on the client’s expecta-
tions (as defined in theAccept request header).


Typical responder methods areformat.htmlandformat.xml, which define responder
blocks for HTML and XML requests, respectively. As these are standard Ruby
method calls, they can be intermingled with other Ruby code such as conditionals.
The block of the first method call matching the request’sAcceptheader will be exe-
cuted. This block usually renders a response in the specified format.


The blocks can also be omitted, in which case the default action is taken (the same
action that would have happened had there been no render or redirect calls in the
action). For example:


respond_to do |format|
format.html # same as format.html { render }
format.xml { render :xml => @product }
end

If all format blocks are the default, a list of types can simply be provided torespond_
to directly, with no block. For example, this code:


respond_to do |format|
format.html
format.xml
end

can be condensed into:


respond_to :html, :xml

The default Rails route has also changed to accommodate different formats. Where
once the default route was/:controller/:action/:id, now it is/:controller/:action
/:id.:format. This passes any provided file extension into the appropriate controller as
params[:format]. This is whatrespond_to uses internally to decide on a response type.


The set of MIME types that Rails recognizes is defined inactionpack/lib/action_
controller/mime_types.rb. Each mapping has a set of MIME types, as well as the Rails
symbol that is used to denote those types (e.g.,:htmlor:xml). At the time of this
writing, the following types are recognized.


Shortcut MIME types
all */*
text text/plain
html text/html, application/xhtml+xml
js text/javascript, application/javascript, application/x-javascript
css text/css
ics text/calendar
csv text/csv
Free download pdf