Sexy REST in Rails
28.01.08Filed Under: Ruby on Rails, blippr
So Rails has the ability to represent a resource in XML pretty easily via the Builder::XmlMarkup class. Rails 2.0 provides the .xml.builder extension, which allows for near-mindless construction of flexible XML views.
Ever wanted to provide the same data in YAML and JSON formats? Find yourself cringing at the thought of rewriting the same view three times for three different formats? Never fear!
By overriding the render method and making use of the Hash.from_xml method, you can provide YAML and JSON equivalents to your XML views without any extra work.
Simply add this to application.rb:
def render(opts = {}, &block)
if opts[:to_yaml] then
headers["Content-Type"] = “text/plain;”
render :text => Hash.from_xml(render_to_string(:template => opts[:to_yaml], :layout => false)).to_yaml, :layout => false
elsif opts[:to_json] then
# headers["Content-Type"] = “text/javascript;”
render :json => Hash.from_xml(render_to_string(:template => opts[:to_json], :layout => false)).to_json, :layout => false
else
super opts, &block
end
end
Now, you can call something like:
respond_to do |wants|
wants.html
wants.xml { render :layout => false }
wants.yaml { render :to_yaml => "nodes/show.xml.builder" }
wants.json { render :to_json => "nodes/show.xml.builder" }
end
And it Just Works™! Very useful if you’re wanting format flexibility without sacrificing a ton of time to get it.
5 Responses to “Sexy REST in Rails”
Leave a Reply
Subscribe to comments feed (this is global, not just for this entry)
cennik…
cennik…
June 16th, 2008 at 1:34 amnoclegi szklarska poreba…
noclegi szklarska poreba…
June 29th, 2008 at 3:52 pmpensjonat szklarska poreba…
pensjonat szklarska poreba…
June 30th, 2008 at 12:16 amantena merlin…
antena merlin telkob…
July 28th, 2008 at 5:38 pmphentermine 375…
order phentermine…
August 4th, 2008 at 12:17 pm