P
A
B
C
A
S
Thoughts, links, pictures on music, food, wine, film, tech etc.

2009-02-09

I wrote this:

Stuffing CouchDB into Rails

Stuffing is a Rails plugin that lets you add a CouchDB data store to an existing ActiveRecord model.

class Post < ActiveRecord::Base stuffing end

The Post model above is just an ordinary ActiveRecord model. It has a MySQL table called "posts" behind it. The fields in the posts table get mapped to methods in instances of Post. But it also has the meta-attribute: stuffing. You can assign a hash of arbitrary keys and values to the stuffing method and it will be persisted automatically to CouchDB.

It works like this:

@post = Post.new({:title => "Cake", :post_type => "recipe", :stuffing => {:ingredients => ['flour','sugar','eggs'], :description => 'mix them all up'}) @post.save @post.stuffing => {:ingredients => ['flour','sugar','eggs'], :description => 'mix them all up'}

When you save this, with @post.save, the :stuffing gets saved to CouchDB. You can retrieve the attributes by accessing the stuffing hash: @post.stuffing['ingredients'] or you can call them by prefixing stuffing_ : @post.stuffing_ingredients. The data gets updated when you update it. It's just like having a big mega-hash in the sky on top of regular old ActiveRecord.

What's the point? Why not just use a CouchDB wrapper like ActiveCouch, CouchRest::Model etc.? Well, CouchDB has a lot of features. It's got javascript views with map-reduce, crash-only design, schema-less documents, bi-directional replication. Lots of really cool stuff that one day we'll all have in our own living rooms. But right now, today, it's only really the schema-less design that appeals to me. I mean, I love the other stuff, but when I'm quickly prototyping an app (as I often am in Rails), I love the idea of just being able to add another field to a form and bam! I have a new attribute. But then I want to be able to quickly hook on all the tried and true ActiveRecord plugins that I'm used to. Hell, I want to be able to call Post.first, Post.last and Post.all.

Stuffing helps to gently add a CouchDB layer to your Rails app without completely removing you from ActiveRecord. Think of it like swimming in CouchDB with arm-bands. Or like a Couch, but without the covers, trimmings or fancy coasters. Just the stuffing.

The plugin is yours, available to enjoy on Github: http://github.com/paulca/stuffing/ where there's a full documentation and some more examples. Feel free to contact me if you have any questions, or fork the project and patch back if you think I screwed something up, or if something can be improved.


 
Made by Paul Campbell. paul@rushedsunlight.com. Twitter. Github.