1 min read

S3 Moneta Store (also, a Rails update)

As I had hoped, moneta has been encouraging various members of the community to play with using a unified key/value abstraction where they would typically have used just a Hash. Both Cloudkit and DataMapper have been playing with using moneta for various parts of their infrastructure, and Anthony Eden just contributed an S3 adapter.

How to use moneta in your own project

It's actually quite simple. Any place where you're currently using or considering using a Hash for its key/value properties, simply continue to use the Hash, but provide a configuration option for swapping in a different object instead.

Here's a potential example from DataMapper. The original code:

def initialize(second_level_cache = nil)
  @cache = {}
  @second_level_cache = second_level_cache
end

And the code with moneta:

module DataMapper
  cattr_accessor :identity_map_klass
  self.identity_map_klass = Hash
end

def initialize(second_level_cache = nil)
  @cache = DataMapper.identity_map_klass.new
  @second_level_cache = second_level_cache
end

As demonstrated above, you can use a bare Hash as a moneta store, with one caveat. A bare Hash does not support Moneta's expiration features. If you want to be able to assume those features, change the above to:

module DataMapper
  cattr_accessor :identity_map_klass
  self.identity_map_klass = Moneta::Memory
end

def initialize(second_level_cache = nil)
  @cache = DataMapper.identity_map_klass.new
  @second_level_cache = second_level_cache
end

Moneta::Memory inherits from Hash, but adds expiration features. Of course, if you go with Moneta::Memory, you will need to include Moneta as a dependency (if you used a bare hash, the user could choose whether or not to use Moneta, but expiration would not be available).

Rails

I've been traveling an insane amount recently, but I've still been working on Rails. I'll have a more thorough post on this soon, but I've started work on a more modular base class for ActionController::Base and ActionMailer::Base that should also serve as a base class for a Rails port of Merb's parts. You can follow along at the abstract_controller branch of my github fork. I pulled in my callbacks branch as well, which is so far working wonderfully on my fork.