ActiveCache

Active cache may be the simple boost for your app. The idea is to store same pages in different states.

Getting started

  1. Install the gem

sudo gem install active_cache
  1. Make sure that you have memcached installed and running

sudo apt-get install memcached
  1. Set cache store in your ‘config/application.rb’ filea

config.active_cache_store = ActiveCache::Store::DalliStore

Sample usage

Let us suppose that you have controller ‘home’ containing action ‘index’ which accepts page parameter do display different content.

Normally you would use

caches_page :index

But this will cause two problems:

  • it will store only first requested page fe: /home/?page=3, so when user will visit /home/?page=4 he would not receive proper content.

  • most time logged in users see pages slightly different, for example user ‘john’ may see information ‘You are signed in as john’

So here comes active_cache, adding line:

class HomeController < ApplicationController

. . .

  active_cache :index, :state => lambda{ |c| {:page => c.params[:page]} }

will cause to store pages dependent of :page. If user visited page /?page=1 - next time he will get this page directly from memory.

Also you may want to use cache only when some condition if satisfied (for example store pages in cache only for guests). This may be done by:

active_cache :index, :state => lambda{ |c| {:page => c.params[:page]} }, :if => lambda{ |c| !c.user_signed_in? }

Next option you can use is :expires_in parameter:

active_cache :index, :state => lambda{ |c| {:page => c.params[:page]} }, :expires_in => 100.seconds

Profit

First action call will write page content into memory.

Example logfile output on first page visit:

Started GET "/?page=144" for 127.0.0.1 at Tue Nov 08 12:41:47 +0100 2011
Processing by HomeController#index as HTML
Parameters: {"page"=>"144"}
Rendered home/index.html.erb within layouts/application (0.1ms)
Completed 200 OK in 50ms (Views: 7.3ms | ActiveRecord: 0.0ms)

Second page visit:

Started GET "/?page=144" for 127.0.0.1 at Tue Nov 08 12:41:50 +0100 2011
Processing by HomeController#index as HTML
Parameters: {"page"=>"144"}
Rendered from memory
Rendered text template (0.0ms)
Completed 200 OK in 6ms (Views: 5.7ms | ActiveRecord: 0.0ms)

so page loading time has been reduced from 50ms to 6ms. Active cache will be cost-effective specially for heavy pages, where lot of content is loaded.

I hope you will find this gem useful.

PLEASE NOTE THAT THIS IS STILL GERM OF AN IDEA THAT MAY BECOME GOOD SOLUTION. I need to write proper tests, add few options like expiration time et caetera.

This project rocks and uses MIT-LICENSE.