Wednesday, March 4, 2009

Spike Sinatra and CouchDB

‹prev | My Chain | next›

Continuing the chain, tonight I do a quick spike of running Sinatra on top of CouchDB.

Much of this is based on the work in

My only goal here was to get a single meal displayed in a browser. Once I have that done, I'll continue this spike by trying out a little cucumber. Soo...

I had previously installed CouchDB. If memory serves, I used the command:
sudo apt-get install couchdb
I love Ubuntu.

With that, I navigated to futon at and create a new database:

Then I created a meal:

And added some attributes:

Just to be sure, I curl the record:
cstrom@jaynestown:~$ curl http://localhost:5984/eee-meals/2005-12-07-breakfast-elves
"_id": "2005-12-07-breakfast-elves",
"_rev": "571520480",
"title": "Breakfast Elves",
"date": "2005-12-07",
"summary": "Field trip bread inspires this post-St. Nicholas Day dinner. Our daughter
returned from her class field trip with a nice little loaf of brown bread.
There was not enough for our not-so-little family, so we also serve pancakes.",
"description": "<p> Yesterday was St. Nicholas Day—better known as Elves's Day
in our family. The kids dutifully placed their Christmas lists in their
stocking and awoke to find the lists replaced by candy and Christmas
ornaments. We hang the ornaments on the Christmas tree tonight.
</p> <p> The baby hurt her leg the other day. Robin was
helping our daughter with some school work when she heard a crash from the
other room. This, of course, is typical in our house, but we grew very
concerned when we realized that the baby could not stand. Happily, she
was inspired by the toys in the pet aisle at Wegmans to try walking
tonight. </p>"
With that I am ready to set up Sinatra and have it pull the meal from CouchDB. First up, install the json and sinatra gems:
gem install sinatra
gem install json
gem install rest-client

At that point, all that's needed is a little standing on the shoulders of giants. RestClient gets the data from CouchDB. JSON parses the data. Then, we render the HTML:
require 'rubygems'
require 'sinatra'
require 'rest_client'
require 'json'

DB = 'http://localhost:5984/eee-meals'

get '/meals/:permalink' do
data = RestClient.get "#{DB}/#{params[:permalink]}"
result = JSON.parse(data)
<p>We enjoyed this meal on #{result['date']}</p>
<p>navigation and links to recipes would go here...</p>
The resulting page is:

Not quite this, but it'll do for a spike.


  1. Thanxs mate !, nice post ...
    I am thinking about building a cms system with sinatra (why should you only use it for small apps ?? ), ruby19, well and couchdb of course ! :P

    i am very curious if the performance will be good enough!..

  2. I did some rudimentary benchmarks, which suggest that the performance should be more than adequate:

    Enjoy -- Sinatra + CouchDB are awesome fun!