Class: ActionDispatch::Session::RedisStore

Inherits:
Rack::Session::Abstract::ID
  • Object
show all
Defined in:
lib/rack-redis-session-store.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ RedisStore

Returns a new instance of RedisStore.



9
10
11
12
13
14
15
# File 'lib/rack-redis-session-store.rb', line 9

def initialize(app, options = {})
  @redis = ConnectionPool.new(:size => options[:max_connections], :timeout => 5) {
    Redis.new(:host => "#{options[:host]}", :port => options[:port], db: options[:db])
  }
  options[:expire_after] ||= 1.day.to_i
  super
end

Instance Method Details

#destroy_session(env, session_id, options) ⇒ Object



49
50
51
52
53
54
# File 'lib/rack-redis-session-store.rb', line 49

def destroy_session(env, session_id, options)
  @redis.with do |redis|
    redis.del(session_id)
    generate_sid unless options[:drop]
  end
end

#generate_sidObject



17
18
19
20
21
22
23
24
# File 'lib/rack-redis-session-store.rb', line 17

def generate_sid
  @redis.with do |redis|
    loop do
      sid = super
      break sid unless redis.get(sid)
    end
  end
end

#get_session(env, sid) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/rack-redis-session-store.rb', line 26

def get_session(env, sid)
  @redis.with do |redis|
    unless sid and session = MultiJson.load(redis.get(sid) || '{}')
      sid, session = generate_sid, {}
    end
    [sid, session]
  end
end

#set_session(env, session_id, new_session, options) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rack-redis-session-store.rb', line 35

def set_session(env, session_id, new_session, options)
  expiry = options[:expire_after]
  expiry = expiry.nil? ? 0 : expiry + 1

  @redis.with do |redis|
    # Due to 53-bit restriction integer in javascript, must provide monkey patch for jbuilder to overcome this issue (by to_s)
    json = Jbuilder.encode do |json|
      json.(new_session, *new_session.keys)
    end
    redis.setex session_id, expiry,json
    session_id
  end
end