Class: Rack::Session::Mongo

Inherits:
Abstract::ID
  • Object
show all
Defined in:
lib/rack/session/mongo.rb,
lib/rack-session-mongo/version.rb

Constant Summary collapse

DEFAULT_OPTIONS =
Abstract::ID::DEFAULT_OPTIONS.merge \
:db_name => :sessions, :collection => :sessions, :marshal_data => true
VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Mongo.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rack/session/mongo.rb', line 13

def initialize(app, options={})
  options = {:db         => options } if options.is_a? ::Mongo::DB
  options = {:connection => options } if options.is_a? ::Mongo::Connection
  super
  db = @default_options[:db] || begin
    conn = @default_options[:connection] || begin
      @default_options[:host] ? ::Mongo::Connection.new(*@default_options[:host].split(':')) : ::Mongo::Connection.new
    end
    conn[@default_options[:db_name].to_s]
  end
  @pool = db[@default_options[:collection].to_s]
  @pool.create_index('sid', :unique => true)
  @mutex = Mutex.new
end

Instance Attribute Details

#mutexObject (readonly)

Returns the value of attribute mutex.



8
9
10
# File 'lib/rack/session/mongo.rb', line 8

def mutex
  @mutex
end

#poolObject (readonly)

Returns the value of attribute pool.



8
9
10
# File 'lib/rack/session/mongo.rb', line 8

def pool
  @pool
end

Instance Method Details

#destroy_session(env, session_id, options) ⇒ Object



52
53
54
55
56
57
# File 'lib/rack/session/mongo.rb', line 52

def destroy_session(env, session_id, options)
  with_lock(env) do
    _delete(session_id)
    generate_sid unless options[:drop]
  end
end

#generate_sidObject



28
29
30
31
32
33
# File 'lib/rack/session/mongo.rb', line 28

def generate_sid
  loop do
    sid = super
    break sid unless _exists? sid
  end
end

#get_session(env, sid) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/rack/session/mongo.rb', line 35

def get_session(env, sid)
  with_lock(env, [nil, {}]) do
    unless sid and session = _get(sid)
      sid, session = generate_sid, {}
      _put sid, session
    end
    [sid, session]
  end
end

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



45
46
47
48
49
50
# File 'lib/rack/session/mongo.rb', line 45

def set_session(env, session_id, new_session, options)
  with_lock(env, false) do
    _put session_id, new_session
    session_id
  end
end

#with_lock(env, default = nil) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/rack/session/mongo.rb', line 59

def with_lock(env, default=nil)
  @mutex.lock if env['rack.multithread']
  yield
rescue
  default
ensure
  @mutex.unlock if @mutex.locked?
end