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'@'%.musc.edu';
dbpass='whatever'
dbuser='user'
host='example.com'
older_than=2 # delete sessions older than this many days
databases=['my_rails_db1','my_rails_db2']
require 'dbi'
date_cutoff = Date.today - older_than
puts "Deleting sessions prior to #{date_cutoff} from:"
databases.each do |db|
dbh=DBI.connect("dbi:Mysql:#{db}:#{host}",dbuser,dbpass)
rows=dbh.do("delete from sessions where updated_at < ?", date_cutoff)
puts "#{db}: #{rows}"
end
puts "Done."
Tag: rails geeky code