OneBody

Auto Expiring Rails Caching

Posted by: timmorgan on: July 21, 2008

Rails has some pretty easy-to-use caching built-in. I don’t know about everyone else, but I know for me, the word “memcache” always scared me. It sounds like some ominous, mysterious, magical thing that takes a Ph.D. to understand.

Rails caching, on the other hand, is just Ruby. And I like Ruby.

But still, it seems to be lacking a useful feature, namely auto expiration of cached items based on a timeframe. Sure, since the cache (in my case at least) is just files on the filesystem, I could set up a cron script to remove files older than X hours or whatever. But that didn’t sound very cool. And I’m all about being cool you know.

So I hacked (and I really mean hacked) together auto expiring action caching for Rails. It works, and it works well for OneBody. But, there are some limitations:

  1. It only works with disk-based cache store.
  2. You must explicitly set the path where you want to store the cached content.
  3. I wrote it, so it’s probably not the “Rails way” of doing things.

But it works. Here is the code.

Using it looks like this:
class PeopleController < ApplicationController
  caches_action :show, :for => 1.hour, \
   :cache_path => "...something here..."
end

I would love to get some feedback. Is this worth anything to anyone?

Tags: ,

Leave a Reply