Programming, Ruby, Scripting, Web Applications

Sinatra example

Since the Sinatra Project website currently seems to have been hijacked and directed to spam (the RubyForge page seems to be fine and is still a good introduction in its own right) I wanted to post an example of how to get going with Sinatra and also to highlight what makes it such a different approach to web frameworks. Here’s the example code on CodeDumper.

I wrote this with JRuby (for the cross-platform win). You’ll need to install the Sinatra, Haml and Mongrel Gems to get it to run.

It uses two styles, first there is the REST-ful extraction of parameters from the url and then there is the form POST submission. In both cases the code is pretty much the same as Sinatra extracts all parameters into the params hash.

I’ve inlined the Haml to make the example simple but normally the view templates would be extracted out of the code into separate files.

Sinatra is sometimes described as being as a web DSL rather than a web framework, it seems apt as it eschews MVC separation but instead by attaching code to routes directly it allows Controller code to be tiny and to delegate appropriately rather than putting in a heavyweight structure that might result in more frameworking code than actual “doing” code.

However one of the things I really like is something you can’t show in a code fragment and that is the ability to dynamically interact with your web application on the fly. Start up Sinatra, change the code of the file you’re running and your changes are reflected immediately. End the compile, deploy, view cycle! It kind of makes web programming fun again.

Standard

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 )

Connecting to %s