Julio's Blog

Follow me at @julio_ody.

Small and sexy

UPDATE: The latest version is now hosted at Forrst.  

Since the days when it was less than very popular, I’ve been a huge fan of Sinatra, among many, many good reasons because:

  • massively sexy HTTP DSL.
  • single file apps. Though I confess I write very few of those, it looks neat because it’s minimal.
  • possibly the thinnest layer between your app and HTTP that can still be called a framework. Think of it as if you’re just being handed the C in MVC. As for the rest, you’ll roll your own.

This minimalism I’m giving such high regard to has nothing to do with performance. It has, however, everything to do with craftmanship. While crafting an app, your mind is set on simplicity and beauty. The difference is similar to what you see between mass produced goods and artisanry.

Rails 3

So we’re more and more seeing news about Rails 3 coming out. Other than being my day job, I haven’t found myself using it since Sinatra happened in my life. But seeing that the minds behind it made all the right decisions they could’ve possibly made, and on top of that Yehuda says the magic words that grab my attention, I set to find out how one can write small, sexy, and functional apps, in a single file, using only what I really need from Rails 3.

For this piglet, I decided for no interface whatsoever. All I want is something I can curl requests at and get JSON responses back. It’ll be a simple HTML page storage REST-ish HTTP interface.

Gist

You can grab the gist here.

The first thing you might notice is it is sexy, but it has love handles. I’m banking on the reason being my lack of understanding of how Rails 3 works. If you know of a better way to do it, hit me up on Twitter.

How it works

Create a config.ru file, and presuming you copied the contents of the gist into a file named “single.rb”, write this in:

$.unshift '.'
require 'single'
run SmallNSexy

Get Unicorn installed. As of when I last tested this example, Webrick failed to recognize any routes that Rails 3 creates. Then in the console:

$ unicorn 

By the way, I’m running Ruby 1.9.2 that I installed via rvm:

$ ruby -v
ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-darwin10.4.0]

So let’s create a document:

$ curl -d 'name=test1&body=stuff written in this document' localhost:8080/pages
{name: test1, body: stuff written in this document}

Retrieving that same document:

$ curl localhost:8080/pages/test1
{"name": "test1", "body": "stuff written in this document"}

Yum!

Yeah but, why?

My own biggest reason for a comeback to Rails is not having to be stuck with that same old way of building Rails apps. All I want is a few classes to handle HTTP-related stuff. I don’t need not even a suggestion for an ORM or a testing framework. I’m into Lego. I’ll assemble what I need quick enough for it not to be a hassle, and fun.