ModelCache

ModelCache is a simple caching plugin for Rails, using memcached. It provides caching abilities for your models, allowing to:

  • cache blocks of code in your model instance methods, based on a generic key (ActiveRecord cache_key is added behind the scenes)
  • cache your instance methods, optionally with a time-to-live setting
  • cache some generic code (e.g. in your class methods)

Both memcached client gems, memcache-client and memcached are supported. You are just expected to create an instance of the client and store it in the CACHE constant.

Installation

As a gem:

gem install model-cache

As a plugin:

script/plugin install git://github.com/moskyt/model_cache.git

or

script/plugin install http://github.com/moskyt/model_cache.git

Example

Create an initializer, for example config/initializers/memcached.rb, containing this code (if you are using memcache-client):

require 'memcache'
CACHE = MemCache.new('127.0.0.1')

or, if using memcached gem:

require 'memcached'
CACHE = Memcached.new('127.0.0.1')

Your model:

class Stuff < ActiveRecord::Base</code>

<code>  def expensive_method
    ...
  end</code>
  
<code>  def another_expensive_method
    ...
  end</code>
  
<code>  cache_method :expensive_method, :another_expensive_method</code>
  
<code>  def third_expensive_method
    ...
  end</code>
  
<code>  cache_method :third_expensive_method, :time => 1.hour</code>
  
<code>  def partially_expensive_method
    ...
    cache :calculation do
      ...
    end
  end</code>
  
<code>  def self.some_class_method
    ModelCache.cache(:this_would_be_persistent, 5.minutes) do
      ...
    end
  end</code>

<code>end

If you want to cache somewhere else than in ActiveRecord::Base classes, you need to include the module explicitly:

class Another
  include ModelCache</code>
  
<code>  def expensive_method
    ...
  end</code>
  
<code>  cache_method :expensive_method  
end

model-cache defines three methods for a cached method:

  • @__uncached_@_method_name_ — the original method without the caching wrapper
  • @__is_cached_@_method_name_@?@ — returns true if this method is cached (with respective arguments)
  • @__flush_@_method_name_ — removes the cache entry explicitly from the cache

Copyright © 2010 Frantisek Havluj, released under the MIT license