Howto Expire ActiveRecordStore Sessions

Posted by ryan
at 10:17 AM on Wednesday, December 21, 2005

Here’s a little tid bit that most will already know, yet is somewhat elusive on a Google search: How to expire old sessions in Rails when you’re using the CGI::Session::ActiveRecordStore session manager?

Doing so is as easy as setting up the following command to run in crontab using the rails provided script/runner:

/usr/bin/ruby /path/to/rails/proj/script/runner
  -e production
  "CGI::Session::ActiveRecordStore::Session.find(:all,
      :conditions => \"updated_at <
        (current_timestamp - interval '1 week')\" 
   ).each do |session|
     session.destroy
   end" 

The above code will find all session overs a week old and delete them. Rails’ script/runner utility loads your whole environment for you, so you have access to all your models if you need to do more complex logic that what I’ve shown above. You can also string that whole command on the same line, I’ve just formatted it to make it easy to follow for you dense folks out there (of which I consider myself one). One other note, the above is for postgresql – I believe to do the same for mysql you will need to use this command:

/usr/bin/ruby /path/to/rails/proj/script/runner
  -e production
  "CGI::Session::ActiveRecordStore::Session.find(:all,
      :conditions => \"date_sub(curdate(), interval 7 day)
        > updated_at\" 
   ).each do |session|
     session.destroy
   end" 
Comments

Leave a response

  1. Lee O'MaraMay 10, 2006 @ 08:22 PM
    How about using destroy_all instead of stepping through the sessions yourself? Also, you can make use of the Rails extensions to integers to do the date calculation. bq. CGI::Session::ActiveRecordStore::Session.destroy_all( ['updated_at < ?', 7.days.ago ] ) Lastly, you might use delete_all if you don't care about callbacks on the session objects.