Class: Tina4::SessionHandlers::FileHandler

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ FileHandler

Returns a new instance of FileHandler.



8
9
10
11
12
# File 'lib/tina4/session_handlers/file_handler.rb', line 8

def initialize(options = {})
  @dir = options[:dir] || File.join(Dir.pwd, "sessions")
  @ttl = options[:ttl] || 86400
  FileUtils.mkdir_p(@dir)
end

Instance Method Details

#cleanupObject



40
41
42
43
44
45
# File 'lib/tina4/session_handlers/file_handler.rb', line 40

def cleanup
  return unless Dir.exist?(@dir)
  Dir.glob(File.join(@dir, "sess_*")).each do |file|
    File.delete(file) if File.mtime(file) + @ttl < Time.now
  end
end

#destroy(session_id) ⇒ Object



35
36
37
38
# File 'lib/tina4/session_handlers/file_handler.rb', line 35

def destroy(session_id)
  path = session_path(session_id)
  File.delete(path) if File.exist?(path)
end

#gc(max_age) ⇒ Object

Garbage-collect expired sessions. Matches the Python interface.

Parameters:

  • max_age (Integer)

    maximum session age in seconds



49
50
51
52
53
54
55
56
57
# File 'lib/tina4/session_handlers/file_handler.rb', line 49

def gc(max_age)
  return unless Dir.exist?(@dir)
  now = Time.now
  Dir.glob(File.join(@dir, "sess_*")).each do |file|
    File.delete(file) if File.mtime(file) + max_age < now
  rescue StandardError
    # Corrupt or locked file — skip
  end
end

#read(session_id) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tina4/session_handlers/file_handler.rb', line 14

def read(session_id)
  path = session_path(session_id)
  return nil unless File.exist?(path)

  # Check expiry
  if File.mtime(path) + @ttl < Time.now
    File.delete(path)
    return nil
  end

  data = File.read(path)
  JSON.parse(data)
rescue JSON::ParserError
  nil
end

#write(session_id, data) ⇒ Object



30
31
32
33
# File 'lib/tina4/session_handlers/file_handler.rb', line 30

def write(session_id, data)
  path = session_path(session_id)
  File.write(path, JSON.generate(data))
end