In memory session store for Rails 3

For the past two days I’ve been playing with the idea of having an in memory session store in a Rails application. Cookies 4KB limit soon became an issue, and I didn’t wan’t to use Redis, Memcached or even database for this. In production, those services have their place for sure, but for development it seems to me that it is silly to ask every developer on the team to have them installed and running to be able to run the application. Development environment is by its nature far from production, even when intentionally similar (e.g same OS), so it makes sense to use as little dependencies as possible.

So, I’ve been searching for in memory session store. At first, there were some references to memory_store, but unfortunately those were all Rails 2 related. There were even some attempts on re-implementing  it in Rails 3, but that of course failed.

Finally, this idea of implementing it for Rails 3 led me to reading Session related code in Rails. And bingo, there it was! Session store in Rails 3 has a couple of implementations, one of them being the CacheStore. And, since there is the in memory cache store in Rails, solution was pretty much straight forward. You can read up on cache store options in Rails here.

In the project, the following changes were needed:

# /config/initializers/session_store.rb
CrazyApp::Application.config.session_store :cache_store

# /config/environments/development.rb
config.cache_store = :memory_store

This will in effect put all your session data in rails process memory. After you kill rails, it all goes away. Ideal for development 🙂

In case you might need the data to persist, you can use file store which will, by default, save the session data in /tmp so you can inspect it. The file store is actually the default cache method.

There is one issue with this setup. You can’t have separate store for session and cache data. In that case, a new session store implementation would be needed, but let’s cross that bridge when the time comes.

Advertisements
Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: