InstantCache provides accessor declarations that permit you to keep instance variables in a memcached cluster rather than local memory.


Mixing in the InstantCache module gives you access to the following declarators:

These allow you to declare instance variables whose values are actually stored in a memcached cluster rather than in local memory. With appropriate naming, this allows you to share instance variables between different objects — even on different systems.


sudo gem install instantcache

The basics

InstantCache works by creating a special blob object and storing it in the instance variable. This blob object intercepts methods aimed at the instance variable and redirects them to a value stored in a memcache cell instead.


The RDoc documentation for InstantCache may be found here

Demonstration of usage

require 'memcache'
require 'instantcache'
class Foo
  include InstantCache
  memcached_accessor(InstantCache::SHARED, :sharedvar)

InstantCache.cache_object ='')

f =
=> nil
f.sharedvar = 17
=> nil
f.sharedvar = [17]
=> [17]
f.sharedvar << 23
=> [17,23]

See the test_multilocking method in the test/test_sharing_complex.rb script for an example/demonstration of variables being shared, locked, and unlocked between different objects and threads.

Common Code
require 'memcache' require 'instantcache' class Foo include InstantCache memcached_accessor(InstantCache::SHARED, :sharedvar) { |vname| "shared-#{vname}" } end   InstantCache.cache_object ='')
Process 1 Process 2
[1] irb> p1 = [2] [3] [4] irb> p1.sharedvar [5] => 23 [6] irb> p1.sharedvar = [1,2,3] [7] => [1, 2, 3] [8] [9] [10] [11] [12] [13] irb> p1.sharedvar [14] => [1, 2, 3, 4] [1] irb> p2 = [2] irb> p2.sharedvar = 23 [3] => 23 [4] [5] [6] [7] [8] irb> p2.sharedvar [9] => [1, 2, 3] [10] [11] irb> p2.sharedvar << 4 [12] => [1, 2, 3, 4] [13] [14]

Forum/Mailing List

How to submit patches

Read the 8 steps for fixing other people’s code and for section 8b: Submit patch to Google Groups, use the Google Group above.

You can fetch the source from either:

TODO – You can not created a RubyForge project, OR have not run rubyforge config
yet to refresh your local rubyforge data with this projects’ id information.

When you do this, this message will magically disappear!

Or you can hack website/index.txt and make it all go away!!

git clone git://

Build and test instructions

cd instantcache
rake test
rake install_gem


This code is free to use under the terms of the Apache Licence V2.0.


Comments are welcome. Send an email to The Rodent of Unusual Size email via the forum

Ken Coar, 11th September 2011
Theme extended from Paul Battley