Skip to content

Commit

Permalink
Handle custom session_class in trim task
Browse files Browse the repository at this point in the history
Better approach to rails#178
  • Loading branch information
ghiculescu committed Mar 10, 2021
1 parent 78e0047 commit c7f1f22
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ You must implement these methods:
* `save`
* `destroy`

Note that some of the provided [rake tasks](https://github.com/rails/activerecord-session_store/blob/master/lib/tasks/database.rake)
require additional methods to be implemented:

* `db:sessions:clear` depends on `table_name`
* `db:sessions:trim` depends on `where` and `delete_all`
* `db:sessions:upgrade` depends on `secure!`

The example SqlBypass class is a generic SQL session store. You may
use it as a basis for high-performance database-specific stores.

Expand Down
4 changes: 2 additions & 2 deletions lib/tasks/database.rake
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ namespace 'db:sessions' do

desc "Clear the sessions table"
task :clear => [:environment, 'db:load_config'] do
ActiveRecord::Base.connection.execute "TRUNCATE TABLE #{ActiveRecord::SessionStore::Session.table_name}"
ActiveRecord::Base.connection.truncate(ActionDispatch::Session::ActiveRecordStore.session_class.table_name)
end

desc "Trim old sessions from the table (default: > 30 days)"
task :trim => [:environment, 'db:load_config'] do
cutoff_period = (ENV['SESSION_DAYS_TRIM_THRESHOLD'] || 30).to_i.days.ago
ActiveRecord::SessionStore::Session.
ActionDispatch::Session::ActiveRecordStore.session_class.
where("updated_at < ?", cutoff_period).
delete_all
end
Expand Down
8 changes: 8 additions & 0 deletions test/tasks/database_rake_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ def test_upgrade_task
assert Session.find_by_session_id(Rack::Session::SessionId.new("original_session_id").private_id)
assert Session.find_by_session_id("2::secure_session_id")
end

def test_clear_task
Session.create!(data: "obsolete")

Rake.application.invoke_task 'db:sessions:clear'

assert_equal 0, Session.count
end
end
end
end

0 comments on commit c7f1f22

Please sign in to comment.