Skip to content

Instantly share code, notes, and snippets.

@manuelmorales
Created January 3, 2012 16:08
Show Gist options
  • Save manuelmorales/1555540 to your computer and use it in GitHub Desktop.
Save manuelmorales/1555540 to your computer and use it in GitHub Desktop.
Deleting old user sessions from Rails database
# app/modes/session.rb
class Session < ActiveRecord::Base
named_scope :unactive_for, lambda{|period| {:conditions => ['sessions.updated_at <= ?', Time.now - period]}}
def self.purge_older_than period
unactive_for(period).find_in_batches do |sessions|
sessions.each{|s| "#{s.id}: s.destroy"}
end
end
end
# Rakefile
desc "Will delete user sessions unactive for specified period as DAYS. Which defaults to 14."
task :purge_old_sessions => [:environment] do
days = if days = ENV['DAYS']
days.to_i
else
14
end
puts "Deleting user sessions last updated more than #{days} days ago. #{Session.unactive_for(days.days).count} in total."
Session.purge_older_than(days.days)
puts "Complete"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment