What's New in Edge Rails: render Now 70% More Betterer

Posted by ryan
at 9:30 AM on Wednesday, April 25, 2007



If you’re anything like me, one of the things that really spins your propeller hat is trying to reduce your code into the least amount of lines possible, while still being completely legible. If you’re not like me, well, ya should be.

To that end, calls to render now have some new possibilities. The first is the ability to specify the Location header value inline with the render call. This is often used when building RESTful services – when an item is created the URI of that new item needs to be sent back in the Location response header:

1
2
3
4
5
@contact = Contact.create(params[:contact])
respond_to do |wants|
  wants.xml { render :xml => @contact.to_xml, :status => :created,
                     :location => contact_url(@contact) }
end

Compare this to what you had to do before, which was manually set the location header prior to calling render:


response.headers["Location"] = contact_url(@contact)

And to compress our render line a little bit more, the to_xml conversion on your model is a bit redundant right? I mean, we’re already telling it to render :xml, shouldn’t it know how to convert the model to render as xml? Yeah, it should, and it does now:


render :xml => @contact, :status => :created, :location => contact_url(@contact)

See how we lost the unnecessary to_xml there? If your model supports to_xml (which all ActiveRecord models do), render :xml will automatically convert it to xml. Ka-boo-ya, 7 characters gone.

tags: ruby, rubyonrails, REST

Comments

Leave a response

  1. Thomas MaasApril 26, 2007 @ 08:33 AM

    Lovely post, especially the first paragraph.

    (Might want to give some dimensions to the comment form textarea in your stylesheet as Safari renders it very small)

  2. Thomas MaasApril 26, 2007 @ 08:46 AM

    Come to think of it, it’s not a css issue but a html one: adding cols and rows attributes to the textarea element should solve it. I’ve send Jeffrey Allan Hardy of scribbish an email. Sorry for this off topic stuff.

  3. RyanApril 26, 2007 @ 09:43 AM

    Hey Thomas – all comments, off topic or not, are welcome. I’ve updated the comment body textarea css to have a width and height – it appears to be fixed in Safari. However, the design definitely does not look as clean and spaced in Safari as it does in other browsers…

    Thanks for the tip!