Deleting Old Ruby on Rails Active Record Sessions Using Whenever and Capistrano
If you’re using the Rails Active Record session store, you’ll notice that it does not delete old sessions. I’ve found this can quickly lead to sessions tables bloated with 100,000 records. I found a good solution on a blog for this, but it required some extra work to get this running with the whenever gem in my Webfaction environment.
- ## First of all this depends on having the javan whenever gem installed:
- ## Capistrano
I’m also assuming you are using Capistrano, throw this in your config/deploy.rb file. You’ll want to modify the path to your copy of whenever. Note that I have this setup to write a new crontab with each deploy.
- ## Deleting The Expired Sessions
The meat and drink of the solution relies on the following one liner, put it in app/lib/delete_expired_sessions.rb:
- ## The Whenever Schedule:
Now add a cron job in your whenever schedule located at config/schedule.rb, again you’ll want to modify the paths to your app and your copy of Ruby:
- ## Verify That It’s Working
Maybe I did this the lazy way, but hey, it works: by temporarily set the cron job to run every 5 minutes and then check the database to make sure the number of sesssions has dropped dramatically. Don’t forget to reset the cron job to run as infrequently as you want.
I am available for Ruby on Rails consulting work – get in touch to learn more.