Simple and fast caching in Rails

I've been setting up some Rails caching code today and found a pretty simple and easy way to implement caching for index page which was taking too much time loading due to some pretty expensive DB queries (accesses, polls counts etc etc).

First of all, there is a very nice article on the subject written by Robert Evans - "Rails Caching" - and you can read about the ways to implement caching of pages, actions and also find a link to a very cool cached.rb gem for model-level caching.

The problem in my case was that Robert's approach (and this approach of of course Rails-recommended) for expiring cached actions is to install a cache sweeper, and in my case, index page was using data from several controllers and installing cache sweepers for all of them is needless overkill. What I wanted is just to add time-expiring action_cache for my site's top page's :index action.

So, here's the bits of code I had to add to my ApplicationController (inside application.rb) in order to make it done:

class ApplicationController < ActionController::Base

@@indexLastCached = Time.now #initializing the last-cached timer
before_filter :index_cache_expirer, :only => [:index] #installing cache-expirer action
caches_action :index  #turning on action cache for action :index

#….. controller code and stuff like that ….. #
def index_cache_expirer
if Time.now-@@indexLastCached>60 # expiring index page every 60 seconds
expire_action :action => :index
@@indexLastCached = Time.now
end
end

Well, now, I'm sure there are much better approaches to caching actions with complicated content (tell me about it?), but the above code works just fine for me and dutifully expires cached action every 60 seconds. Thanks to that, my requests-per-second count increased from 0.61 req/sec to value near 36 req/sec. Pretty cool huh?

Leave a Reply