Class: Tina4::SessionHandlers::FileHandler
- Inherits:
-
Object
- Object
- Tina4::SessionHandlers::FileHandler
- Defined in:
- lib/tina4/session_handlers/file_handler.rb
Instance Method Summary collapse
- #cleanup ⇒ Object
- #destroy(session_id) ⇒ Object
-
#gc(max_age) ⇒ Object
Garbage-collect expired sessions.
-
#initialize(options = {}) ⇒ FileHandler
constructor
A new instance of FileHandler.
- #read(session_id) ⇒ Object
- #write(session_id, data) ⇒ Object
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( = {}) @dir = [:dir] || File.join(Dir.pwd, "sessions") @ttl = [:ttl] || 86400 FileUtils.mkdir_p(@dir) end |
Instance Method Details
#cleanup ⇒ Object
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.
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 |