[Rails] respond_to and Accept headers

Jean-François jf.web3 at gmail.com
Wed Jun 28 09:24:52 GMT 2006


Hello Eduardo,

> After reading:
>
> <http://www.loudthinking.com/arc/000572.html>

In fact, some improvements have been made in trunk, so with the
new rewriting of Routes, there's a new functionality taht will interest you.

> I'm trying to experiment with respond_to in order to not repeat myself
> and create atom feeds out of a "browse" view.
>
> In application controller I created a before filter that checks for the
> extension of the current url and changes the accept header:

Now with 1.1.3, you don't need to do this workaround and set
the Accept header in a before_filter

The Accept header sent by the client can be bypassed
if the file extension is provided in the url :

with the route :
map.connect '/foo/:id.:format', :controller => 'foo', :action => 'bar'

so your route must have :format in it.

with in FooController :

def bar
  @foo = Foo.find(params[:id])
  respond_to do |wants|
    wants.html # returns html
    wants.xml { render :xml => @foo.to_xml } # returns xml
    wants.rss { render :action => "rss", :content_type => Mime::RSS }
    wants.atom {render :action => "atom", :content_type => Mime::ATOM }
  end
end

you don't even need to know the correct mime type, with :content_type =>
MIME::ATOM, the response will have the content type header automatically
set with 'application/xml+atom'

So if the client sends the url /foo/1 with Accept text/html, it will
return html,
if the client sends the url /foo/1 with Accept text/xml it will return xml,
if the client sends the url /foo/1.xml with Accept text/html, Rails
will not examine
Accept and return XML
if the client sends the url /foo/1.atom, Rails will return an Atom file.

assuming 'rss' action with relative view return a rss file, the same
for 'atom' action.

This is a very new feature, I haven't tested yet, my explanation may have some
mistakes, but the idea is here. For the moment, the best documentation
is the Rails source itself. See changeset 4394.

You will make Atom feeds easily with that,

   -- Jean-François.

-- 
À la renverse.


More information about the Rails mailing list