Wrapping get, post, put, delete – Add Magic JSON Power
Several times recently, there have been questions in the #sinatra channel, and on the mailing list about how to automatically render JSON, or any other kind of format as the response from Sinatra.
My favorite way of accomplishing this is to wrap the normal get and post methods with additional JSON abilities.
require 'rubygems' require 'sinatra' require 'json' def json_get(route, options={}, &block) get(route, options) do block.call.to_json end end json_get '/' do {"bar" => "baz", "foo" => "bar"} end
And of course, this can be expanded to other cases where you’d want to pre-process or post-process certain routes. You could easily define an admin_get that checks that the user is logged in as an admin. Or an xml_get, or a timed_get method.
October 27th, 2009 at 11:23 am
This is really handy, but it seems to break if you use any helpers in your route. Is there any way to get to helpers with this kind of wrapper?
October 27th, 2009 at 3:16 pm
Nicolás Sanguinetti helpfully solved this problem for me. Thanks again for the original code. http://groups.google.com/group/sinatrarb/msg/bb1219bd6c990b4d