Monday 19 March 2012

Rails 3: Memcached server

Rails 3 uses :cookie_store as its default way of storing session values i.e., the session variables are stored in client side browser cookies. So even after the server is restarted the previous session variables persists. To avoid this I used memcached server for rails 3 session store.

Steps for using :memcache_store in rails 3:
1. Install memcached server of 1.4.x or higher version, for installation refer http://lang-asa.blogspot.in/2010/02/memcached-on-mac-and-windows-7.html.

2. Add gem 'dalli' in gemfile and run bundle install.

3. Replace the line on config/initializers/session_store.rb
    SampleApp::Application.config.session_store :cookie_store
    with this line
    SampleApp::Application.config.session_store  :dalli_store

4. Add these lines to config/environment.rb
    require 'action_dispatch/middleware/session/dalli_store'
    CACHE = Dalli::Client.new(:namespace => "SampleApp", :memcache_server => ['127.0.0.1:11211'])

5. Now start the memcached server installed on your machine.

Success!, now you are ready to run the Rails 3 application.

If you are wishing to deploy the application to heroku, just refer this http://devcenter.heroku.com/articles/memcache