Prev | Current Page 331 | Next

Brad Ediger

"Advanced Rails"


Typical responder methods are format.html and format.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??™s Accept header will be executed.
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 to respond_
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 what respond_to uses internally to decide on a response type.
The set of MIME types that Rails recognizes is defined in actionpack/lib/action_
controller/mime_types.


Pages:
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343