Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
9 changes: 7 additions & 2 deletions lib/tasks/database.rake
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@ 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}"
if ActiveRecord::Base.connection.respond_to?(:truncate)
# Rails 6+
ActiveRecord::Base.connection.truncate(ActionDispatch::Session::ActiveRecordStore.session_class.table_name)
else
ActiveRecord::Base.connection.execute "TRUNCATE TABLE #{ActiveRecord::SessionStore::Session.table_name}"
end
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