Supermodel: Simple ActiveModel-Powered In-Memory Models
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.
Supermodel shows a lot of promise and is what I was originally hoping ActiveModel
was going to be. It provides just the right level of abstraction and separation from the database, but without losing the goodness we came to enjoy from ActiveRecord over the past few years.
March 26, 2010 at 7:17 pm
Very cool stuff.
March 26, 2010 at 9:29 pm
Thanks Peter,
I've also re-written it in JavaScript for those people doing web applications:
http://github.com/maccman/supermodel-js
It speeds up development considerably - check out the source of http://github.com/maccman/ymockup for a good example.
March 27, 2010 at 8:44 am
if you are specifically looking for an object-redis-mapper, you might also want to check out ohm, or my freshly released
http://github.com/tlossen/remodel
"a minimal ORM in less than 300 lines of ruby" -- including full association support.