Satya's blog - Rails session reaper

Aug 28 2009 11:04 Rails session reaper

Ever had a need for a cron job that goes into your Ruby on Rails databases and deletes stale sessions? Yeah, maybe there are other solutions. I just came up with this simple Ruby script. Being Ruby, it shouldn't necessarily be anywhere in your Rails applications.

# Cron job to delete sessions from rails apps. Deletes any session which hasn't
# been touched since "older_than" days. You have to grant the special user
# permission with this SQL: GRANT SELECT (`updated_at`), DELETE ON
# `table_name`.`sessions` TO 'username'@'';
older_than=2 # delete sessions older than this many days

require 'dbi'
date_cutoff = - older_than
puts "Deleting sessions prior to #{date_cutoff} from:"

databases.each do |db|
    dbh=DBI.connect("dbi:Mysql:#{db}:#{host}",dbuser,dbpass)"delete from sessions where updated_at < ?", date_cutoff)
    puts "#{db}: #{rows}"
puts "Done."

Tag: rails geeky code