Rails using memcache for everything

January 13, 2006 Link to post  Permalink

The Rails documentation for using memcache is a little skimpy. I eventually worked out how to use it for a Session store by googling. The Fragment cache store was a little easier.

Here’s the relevant parts of my environment.rb file:

 1equire 'memcache'
 2
 3memcache_options = {
 4   :compression => false,
 5   :debug => false,
 6   :namespace => "app-#{RAILS_ENV}",
 7   :readonly => false,
 8   :urlencode => false
 9}
10memcache_servers = [ '192.168.1.150:2222', '192.168.1.150:2223' ]
11
12Rails::Initializer.run do |config|
13  ....
14  config.action_controller.session_store = :mem_cache_store
15  ...
16  config.action_controller.fragment_cache_store = :mem_cache_store, memcache_servers, memcache_options
17  ...
18end
19
20...
21cache_params = *([memcache_servers, memcache_options].flatten)
22CACHE = MemCache.new *cache_params
23ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.merge!({ 'cache' => CACHE })

The order of these things is important – the DEFAULT_SESSION_OPTIONS can’t be changed until after the Initializer has finished, for instance.

This configuration gives me:

  1. Session store in Memcache
  2. Fragment cache in Memcache
  3. A global CACHE object I can use to cache Model objects

It’s annoying that the configuration for the Session store and Fragment cache aren’t the same – oh well.

Update: Fixed a bug in the passing of parameters to the setup of the CACHE object.