Created
January 3, 2012 16:08
-
-
Save manuelmorales/1555540 to your computer and use it in GitHub Desktop.
Deleting old user sessions from Rails database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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