Fun with Sinatra

A few days ago I started playing with Sinatra, very small, but very nice Ruby web framework. It takes about 15 minutes to read the book and get started. Since I’ve been using Rails for some time now, I started to wonder: what would it take to implement something similar to Rails respond_to functionality… This is what I’ve got so far:

helpers do

def respond_to(&block)
class << (mappings = {} )
def method_missing(name, &resp)
self[name.to_s] = Proc.new(&resp)
end
end
yield mappings
handler = mappings[params[‘format’]] if params[‘format’]
handler.call if handler
end

end

This will add a helper method, which can be used in all routes. Now, we need to add a before filter to make sure format is added to the request_path:

before do
ext = request.path_info =~ /.*([.]([^.]*))$/ ? $1 : ‘.html’
request.path_info = request.path_info + ext unless $1
content_type ext
end

All there is left to do is to define a route, which will allow for format parameter, and use our helper method:

get ‘/hello.:format’ do
respond_to do |format|
format.html { “You have requested HTML format” }
format.json { { :message => ‘hello’ }.to_json }
format.xml  { “<hello />”}
end
end

Now it looks more like Rails 😉

Advertisements