Skip to content

Commit

Permalink
Add :ttl configuration option (#84)
Browse files Browse the repository at this point in the history
**Why**: The :expire_after config option controls both the Redis
session expiration and the expiration of the Rails session cookie.
Adding a new config option :ttl allows those controls to be
managed separately.

The most common case would be if you wanted the Rails cookie
to expire when the browser is closed, as it would if :expire_after
were set to `nil`.
  • Loading branch information
pkarman authored and Jesterovskiy committed Aug 9, 2018
1 parent 1e52073 commit 428b57e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -36,7 +36,8 @@ In your Rails app, throw in an initializer with the following contents:
Rails.application.config.session_store :redis_session_store, {
key: 'your_session_key',
redis: {
expire_after: 120.minutes,
expire_after: 120.minutes, # cookie expiration
ttl: 120.minutes, # Redis expiration, defaults to 'expire_after'
key_prefix: 'myapp:session:',
url: 'redis://localhost:6379/0',
}
Expand Down
7 changes: 6 additions & 1 deletion lib/redis-session-store.rb
Expand Up @@ -116,7 +116,7 @@ def decode(data)
end

def set_session(env, sid, session_data, options = nil)
expiry = (options || env.fetch(ENV_SESSION_OPTIONS_KEY))[:expire_after]
expiry = get_expiry(env, options)
if expiry
redis.setex(prefixed(sid), expiry, encode(session_data))
else
Expand All @@ -129,6 +129,11 @@ def set_session(env, sid, session_data, options = nil)
end
alias write_session set_session

def get_expiry(env, options)
session_storage_options = options || env.fetch(ENV_SESSION_OPTIONS_KEY, {})
session_storage_options[:ttl] || session_storage_options[:expire_after]
end

def encode(session_data)
serializer.dump(session_data)
end
Expand Down
23 changes: 23 additions & 0 deletions spec/redis_session_store_spec.rb
Expand Up @@ -59,6 +59,29 @@
end
end

describe 'when configured with both :ttl and :expire_after' do
let(:ttl_seconds) { 60 * 120 }
let :options do
{
key: random_string,
secret: random_string,
redis: {
host: 'hosty.local',
port: 16_379,
db: 2,
key_prefix: 'myapp:session:',
ttl: ttl_seconds,
expire_after: nil
}
}
end

it 'assigns the :ttl option to @default_options' do
expect(default_options[:ttl]).to eq(ttl_seconds)
expect(default_options[:expire_after]).to be_nil
end
end

describe 'when initializing with top-level redis options' do
let :options do
{
Expand Down

0 comments on commit 428b57e

Please sign in to comment.