views:

1387

answers:

5

I'm currently using the ActiveRecord-based session store for my Rails app and I have a background process which clears out inactive sessions every 30 minutes.

I'd like to switch to Rails' new cookie-based session store but how do I set the expiry time of the session to 30 minutes, as opposed to the default 'at end of session' value?

+2  A: 

The session options page on the Rails wiki hints that this is only possible through a plugin:


Set the session cookie expire time

Unfortunately Rails has no way to dynamically set the expiry time of the session cookie. So it is recommended that you use the following plugin, which allows you to accomplish it: http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/


Of course take into account that the plugin is old, and may not work with your current version of Rails (I haven't looked at the specifics)

Gareth
+1  A: 

You could try adding the following line to your environment.rb file:

session :session_key => 'my_session_key'
session :session_expires => 1.day.from_now

Alternatively, you can set the session options as follows:

ActionController::Base.session_options[:session_expires] = 1.day.from_now

I've not tested this thouroughly, so YMMV.

Mr. Matt
+3  A: 

Ideally, you'd want to add something like this to environment.rb:

session :session_expires => 1.day.from_now

But that won't work because the code is only run once when the APP is started and thus the next day all your sessions are being created with an expiration in the past.

I usually set the session_expires to some time far in the future (6 months). Then manually set and check a session[:expires] date in a before_filter on my application controller and reset the session when that date has passed.

This makes it VERY easy to add a 'Keep me logged in for ___' option when signing in, you just set session[:expires] = Time.now + ___

Daniel Beardsley
A: 

Use this, it's working for me in rails 2.1.x:

SlidingSessions

I currently have cookies set to expire exactly 2 weeks after a user logs in, and setting it to 30 minutes is simple.

Allan L.
+1  A: 

I stumbled across this question after a conversation in the office. Just for the sake of completeness, I've discovered that it is possible to expire sessions after a period of inactivity and it's built into Rails. In config/environment.rb, do something along the lines of:

config.action_controller.session = {
  :key          => 'whatever',
  :secret       => 'nottellingyou',
  :expire_after => 30.minutes
}

Check out lib/action_controller/session/cookie_store.rb#114 for the (apparently undocumented) option in action. Looks like it's been around since the move to Rack sessions back in December 2008.

Graeme Mathieson