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



56
57
58
59
60
61
62
# File 'lib/rack-redis-session-store.rb', line 56

def destroy_session(env, session_id, options)
  puts('Destroy session')
  @redis.with do |redis|
    redis.del(session_id)
  end
  generate_sid unless options[:drop]
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
34
35
36
37
38
39
40
# File 'lib/rack-redis-session-store.rb', line 26

def get_session(env, sid)
  session = {}
  if sid!='null'
    @redis.with do |redis|
      options = env['rack.session.options']
      session_string = redis.get(sid)
      if session_string
        session = JSON.parse(session_string)
      end
    end
  else
    sid = generate_sid
  end
  [sid, session]
end

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



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rack-redis-session-store.rb', line 42

def set_session(env, session_id, new_session, options)
  if (!new_session.empty?)
    @redis.with do |redis|
      json = Jbuilder.encode do |json|
        json.(new_session, *new_session.keys)
      end
      redis.setex session_id, options[:expire_after],json
    end
  end
  #For some reason, rack doesn't set new session_id to options[:id]
  options[:id] = session_id
  return true
end