Thursday 3 September 2009

Purging sessions in rails

Keeping it simple we first create a script:

logger = Logger.new("#{RAILS_ROOT}/log/sessions_purge.log")
logger.formatter = Logger::Formatter.new()

older_than = Date.today - 1

logger.info "Starting to purge sessions older than #{older_than}"

counter = 0
ActiveRecord::SessionStore::Session.find_by_sql(["SELECT * FROM sessions WHERE updated_at < ?", older_than]).each do |r|
counter += 1
begin
r.destroy
rescue Exception => e
logger.error "Unable to remove #{r.key} #{e}"
end
end

logger.info "Removed #{counter} sessions"

Which needs to be run from the users crontab

@daily (cd /home/project ; /usr/local/bin/ruby script/runner -e production script/crons/session_purge.rb)

If ActiveRecord::SessionStore::Session doesn't work for you then create a model for the sessions, ruby script/generate model session, and replace it with Session

No comments:

Post a Comment