October 23, 2006 22:48
Posted by Jeremy Durham
A while ago I wrote a little block of code about dynamically caching class methods, and I finally got a bit of time to clean it up; here’s basically how it works:
In environment.rb, setup memcache:
# MemcacheCACHE = MemCache.newCACHE.servers = ['memcache101:11211', 'memcache102:11211']
And a hyphothentical class method:
def self.member_countmember_count = Account.count(:conditions => "zipcode != ''")end
And this at the bottom of the class to cache the method:
Or, a more interesting example:
def self.members_by_region(region)member_count = Account.count(:all,:conditions => ["state in (?) AND accounts.zipcode != ''", region],:include => [:zipcode])end
And caching it is the same:
The caching is even aware of different parameters. for example, members_by_region(‘MA’) is cached, as well as members_by_region(‘MI’) is cached, separately.
And if you’d like, you can directly call the non-cached method if you require the data to be fresh:
cache_method also accepts a :duration option for how long you’d like to cache the item; the default is 24 hours.
cache_method :member_count, :duration => 2.hours
If it sounds at all useful, it’s available as a plugin