Dynamic session expiration times with Rails
One of the problems with Rails that I’ve been running into recently deal with sessions–they never seem to last long enough. For long-term data, cookies are appropriate, but for an app I’ve been working on I wanted users to be able to return to their state even after a few days.
Setting the expiration date for session cookies isn’t particular difficult in Rails: pass a Time object in your config/environment.rb and you’re off and running. That works if you want your sessions to expire in two years, say, but what happens if you want your sessions to expire in a week? Wouldn’t Time.now + 1.week work? No, because the environment code is executed just the once, and unless you’re kicking your FastCGI processes over every day or so, your app will eventually be serving up session cookies that expire last Tuesday. And that’s bad. So what’s a boy to do?
Write a plugin, that’s what.
Dynamic Session Expiration! A Plugin! For Rails!
Here we go!
Installation
Got your project under Subversion source control like a good little railer?
./script/plugin install -x http://svn.codahale.com/dynamic_session_exp/trunk
Don’t use Subversion, because source control is for weaklings?
./script/plugin install http://svn.codahale.com/dynamic_session_exp/trunk
Configuration
Now, let us away to the config/environment.rb!
CGI::Session.expire_after 1.month
This does pretty much exactly what it looks like. Session cookies are served up with an expiration date set to one month after the current time.
Conclusion
I’m a little concerned that maybe there’s some really graceful way of getting Rails to deal with session cookies a bit better, or that maybe I’m ignoring some really reasonable design spec in doing this, but hey. I need this functionality, so here it is. And it’s here for you too if you need it. I haven’t written any documentation for this because it’s so damn simple.
(FYI, this is copyright © 2006, but released under the generous and humane terms of the MIT License, copies of which can be found in various places throughout the intarweb. Bombs away!)
31 comments »