Class: Rack::Session::Redis

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

Defined Under Namespace

Classes: MarshalledRedis

Constant Summary collapse

DEFAULT_OPTIONS =
Abstract::ID::DEFAULT_OPTIONS.merge(
  :drop      => false,
  :url       => "redis://127.0.0.1:6379/0",
  :namespace => "rack:session"
)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Redis.



53
54
55
56
57
58
59
60
61
# File 'lib/rack/session/redis.rb', line 53

def initialize(app, options={})
  super

  @redis     = MarshalledRedis.connect(
    :namespace => default_options[:namespace],
    :url       => default_options[:url]
  )
  @mutex     = Mutex.new
end

Instance Attribute Details

#mutexObject (readonly)

Returns the value of attribute mutex.



46
47
48
# File 'lib/rack/session/redis.rb', line 46

def mutex
  @mutex
end

#redisObject (readonly)

Returns the value of attribute redis.



46
47
48
# File 'lib/rack/session/redis.rb', line 46

def redis
  @redis
end

Instance Method Details

#generate_sidObject



63
64
65
66
67
68
# File 'lib/rack/session/redis.rb', line 63

def generate_sid
  loop do
    sid = super
    break sid unless @redis.exists(sid)
  end
end

#get_session(env, sid) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/rack/session/redis.rb', line 70

def get_session(env, sid)
  session = @redis.get(sid) if sid
  @mutex.lock if env['rack.multithread']
  unless sid and session
    env['rack.errors'].puts("Session '#{sid.inspect}' not found, initializing...") if $VERBOSE and not sid.nil?
    session = {}
    sid = generate_sid
    @redis.set sid, session
  end
  session.instance_variable_set('@old', {}.merge(session))
  return [sid, session]
ensure
  @mutex.unlock if env['rack.multithread']
end

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



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/rack/session/redis.rb', line 85

def set_session(env, session_id, new_session, options)
  @mutex.lock if env['rack.multithread']
  session = @redis.get(session_id)
  if options[:renew] or options[:drop]
    @redis.del session_id
    return false if options[:drop]
    session_id = generate_sid
    @redis.set session_id, 0
  end
  old_session = new_session.instance_variable_get('@old') || {}
  session = merge_sessions session_id, old_session, new_session, session
  if options[:expire_after].to_i > 0
    @redis.setex session_id, options[:expire_after], session
  else
    @redis.set session_id, session
  end
  return session_id
rescue => e
  puts e
  puts e.backtrace
  warn "#{new_session.inspect} has been lost."
  warn $!.inspect
ensure
  @mutex.unlock if env['rack.multithread']
end