Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle custom session_class in all rake tasks #179

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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