Class: Rack::Session::Pool

Inherits:
Abstract::ID show all
Defined in:
lib/rack/session/pool.rb

Overview

Rack::Session::Pool provides simple cookie based session management. Session data is stored in a hash held by @pool. In the context of a multithreaded environment, sessions being committed to the pool is done in a merging manner.

The :drop option is available in rack.session.options if you wish to explicitly remove the session from the session cache.

Example:

myapp = MyRackApp.new
sessioned = Rack::Session::Pool.new(myapp,
  :domain => 'foo.com',
  :expire_after => 2592000
)
Rack::Handler::WEBrick.run sessioned

Constant Summary collapse

DEFAULT_OPTIONS =
Abstract::ID::DEFAULT_OPTIONS.merge :drop => false

Instance Attribute Summary collapse

Attributes inherited from Abstract::ID

#default_options, #key

Instance Method Summary collapse

Methods inherited from Abstract::ID

#call, #context

Constructor Details

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

Returns a new instance of Pool.


31
32
33
34
35
# File 'lib/rack/session/pool.rb', line 31

def initialize(app, options={})
  super
  @pool = Hash.new
  @mutex = Mutex.new
end

Instance Attribute Details

#mutexObject (readonly)

Returns the value of attribute mutex


28
29
30
# File 'lib/rack/session/pool.rb', line 28

def mutex
  @mutex
end

#poolObject (readonly)

Returns the value of attribute pool


28
29
30
# File 'lib/rack/session/pool.rb', line 28

def pool
  @pool
end

Instance Method Details

#generate_sidObject


37
38
39
40
41
42
# File 'lib/rack/session/pool.rb', line 37

def generate_sid
  loop do
    sid = super
    break sid unless @pool.key? sid
  end
end

#get_session(env, sid) ⇒ Object


44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rack/session/pool.rb', line 44

def get_session(env, sid)
  session = @pool[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
    @pool.store 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


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/rack/session/pool.rb', line 59

def set_session(env, session_id, new_session, options)
  @mutex.lock if env['rack.multithread']
  session = @pool[session_id]
  if options[:renew] or options[:drop]
    @pool.delete session_id
    return false if options[:drop]
    session_id = generate_sid
    @pool.store session_id, 0
  end
  old_session = new_session.instance_variable_get('@old') || {}
  session = merge_sessions session_id, old_session, new_session, session
  @pool.store session_id, session
  return session_id
rescue
  warn "#{new_session.inspect} has been lost."
  warn $!.inspect
ensure
  @mutex.unlock if env['rack.multithread']
end