Disabling Sessions

October 21, 2010 at 5:45 AM

This is part of a series on Rails 2 Upgrade Turbulence.

Urbanspoon uses sessions to store various bits of information in the database that users might want to see again. We have a neat hack that Adam wrote to turn off sessions for bots so that we don't need to touch that table unless necessary.

Unfortunately, his trick depends on the Rails 1.x ability to toggle sessions progammatically. Rails 2 opted for lazy loading – if you don't access it, it never gets loaded. There is, in fact, no out-of-the-box way to disable the session progammatically at request time.

The trick I used to make this work is simple: choose the session store for a given request in a before_filter. I made a simple session that dumps all its data into a Hash, but never persists anything.

I then created a subclass of our session store (SqlSessionStore, in our case) that has a class-level toggle ("disabled") which it uses to choose the backing session class when it is called.

I now use a before filter to enable or disable sessions even for code paths that attempt to access them.