Sexy REST in Rails

28.01.08

Filed 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”

  1. cennik

    cennik…

    cennik…

  2. noclegi szklarska poreba

    noclegi szklarska poreba…

    noclegi szklarska poreba…

  3. pensjonat szklarska poreba

    pensjonat szklarska poreba…

    pensjonat szklarska poreba…

  4. antena merlin xu870 telkob

    antena merlin…

    antena merlin telkob…

  5. phentermine

    phentermine 375…

    order phentermine…

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to comments feed (this is global, not just for this entry)

Categories