Class: Tina4::SessionHandlers::MongoHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/tina4/session_handlers/mongo_handler.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ MongoHandler

Returns a new instance of MongoHandler.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/tina4/session_handlers/mongo_handler.rb', line 7

def initialize(options = {})
  require "mongo"
  @ttl = options[:ttl] || 86400
  client = Mongo::Client.new(
    options[:uri] || "mongodb://localhost:27017",
    database: options[:database] || "tina4_sessions"
  )
  @collection = client[options[:collection] || "sessions"]
  # Ensure TTL index
  @collection.indexes.create_one(
    { updated_at: 1 },
    expire_after_seconds: @ttl
  )
rescue LoadError
  raise "MongoDB session handler requires the 'mongo' gem. Install with: gem install mongo"
rescue Mongo::Error => e
  Tina4::Log.error("MongoDB session setup failed: #{e.message}")
end

Instance Method Details

#cleanupObject



44
45
46
# File 'lib/tina4/session_handlers/mongo_handler.rb', line 44

def cleanup
  # MongoDB TTL index handles cleanup
end

#destroy(session_id) ⇒ Object



40
41
42
# File 'lib/tina4/session_handlers/mongo_handler.rb', line 40

def destroy(session_id)
  @collection.delete_one(_id: session_id)
end

#read(session_id) ⇒ Object



26
27
28
29
30
# File 'lib/tina4/session_handlers/mongo_handler.rb', line 26

def read(session_id)
  doc = @collection.find(_id: session_id).first
  return nil unless doc
  doc["data"]
end

#write(session_id, data) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/tina4/session_handlers/mongo_handler.rb', line 32

def write(session_id, data)
  @collection.update_one(
    { _id: session_id },
    { "$set" => { data: data, updated_at: Time.now } },
    upsert: true
  )
end