Skip to content

Commit bdd1b2b

Browse files
author
Peter Karman
committed
Add :ttl configuration option
**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`.
1 parent 5667173 commit bdd1b2b

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ In your Rails app, throw in an initializer with the following contents:
3636
My::Application.config.session_store :redis_session_store, {
3737
key: 'your_session_key',
3838
redis: {
39-
expire_after: 120.minutes,
39+
expire_after: 120.minutes, # cookie expiration
40+
ttl: 120.minutes, # Redis expiration
4041
key_prefix: 'myapp:session:',
4142
url: 'redis://host:12345/2',
4243
}

lib/redis-session-store.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def decode(data)
115115
end
116116

117117
def set_session(env, sid, session_data, options = nil)
118-
expiry = (options || env.fetch(ENV_SESSION_OPTIONS_KEY))[:expire_after]
118+
expiry = get_expiry(env, options)
119119
if expiry
120120
redis.setex(prefixed(sid), expiry, encode(session_data))
121121
else
@@ -128,6 +128,11 @@ def set_session(env, sid, session_data, options = nil)
128128
end
129129
alias write_session set_session
130130

131+
def get_expiry(env, options)
132+
session_storage_options = options || env.fetch(ENV_SESSION_OPTIONS_KEY, {})
133+
session_storage_options[:ttl] || session_storage_options[:expire_after]
134+
end
135+
131136
def encode(session_data)
132137
serializer.dump(session_data)
133138
end

spec/redis_session_store_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,29 @@
5959
end
6060
end
6161

62+
describe 'when configured with both :ttl and :expire_after' do
63+
let(:ttl_seconds) { 60 * 120 }
64+
let :options do
65+
{
66+
key: random_string,
67+
secret: random_string,
68+
redis: {
69+
host: 'hosty.local',
70+
port: 16_379,
71+
db: 2,
72+
key_prefix: 'myapp:session:',
73+
ttl: ttl_seconds,
74+
expire_after: nil
75+
}
76+
}
77+
end
78+
79+
it 'assigns the :ttl option to @default_options' do
80+
expect(default_options[:ttl]).to eq(ttl_seconds)
81+
expect(default_options[:expire_after]).to be_nil
82+
end
83+
end
84+
6285
describe 'when initializing with top-level redis options' do
6386
let :options do
6487
{

0 commit comments

Comments
 (0)