Supermodel: Simple ActiveModel-Powered In-Memory Models

By Peter Cooper

Supermodel is a new library by Alex Maccaw that uses the Rails 3.0 ActiveModel library to provide ActiveRecord-esque in-memory "database" storage in Ruby.

Supermodel is best demonstrated with a basic example:

require 'supermodel' class Person < SuperModel::Base; end a = Person.new( :name => "Jim" ) a.save Person.find_by_name('Jim') # => #<Person> Person.all # => [#<Person>]

This is just the start! Out of the box, Supermodel supports validations, callbacks, observers, dirty change tracking, and serialization. It also allows you, with only a little magic, to go beyond ephemeral memory-only structures and marshall your SuperModel-based objects to disk or even to a Redis store.

A more complex example that includes randomly generated IDs and validations:

require 'supermodel' class Person < SuperModel::Base include SuperModel::RandomID attributes :name validates_presence_of :name end a = Person.new a.valid? # => false a.name = "Jim" a.valid? # => true a.save a.id # => "6481a4fcd834e567836587c6da"

It's early days for Supermodel, but I can see it becoming a big deal for Rubyists away from the Rails stack. The gemified version doesn't have support for relationships yet, but the edge version on GitHub has early support for belongs_to and has_many included.Alex has written the code in a well structured way and creating modules or subclasses to add support for interacting with other backends (such as, say, Tokyo Cabinet) doesn't look like it'd be too hard.