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

About Wondering Bear
39 years old male bear.

2 Responses to Fun with Sinatra

  1. Nice implementation. What I like most is how you access to the mappings singleton class, while actually initializing it to an empty hash.
    I’d only simplify the Regexp into /(\.[^\.]+)$/. 🙂

    Why don’t you propose this helper on to the sinatra authors? It would be useful, IMHO.

    Bye!

    • Wondering Bear says:

      Thanks Marcello,

      As you suggested I’ve posted note to the Sinatra mailing list. I will also use your regex now 😉

      Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: