Class: Tina4::Session

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

Constant Summary collapse

DEFAULT_OPTIONS =
{
  cookie_name: "tina4_session",
  secret: nil,
  max_age: 86400,
  handler: :file,
  handler_options: {}
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, options = {}) ⇒ Session

Returns a new instance of Session.



17
18
19
20
21
22
23
24
# File 'lib/tina4/session.rb', line 17

def initialize(env, options = {})
  @options = DEFAULT_OPTIONS.merge(options)
  @options[:secret] ||= ENV["SECRET"] || "tina4-default-secret"
  @handler = create_handler
  @id = extract_session_id(env) || SecureRandom.hex(32)
  @data = load_session
  @modified = false
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



15
16
17
# File 'lib/tina4/session.rb', line 15

def data
  @data
end

#idObject (readonly)

Returns the value of attribute id.



15
16
17
# File 'lib/tina4/session.rb', line 15

def id
  @id
end

Instance Method Details

#[](key) ⇒ Object



26
27
28
# File 'lib/tina4/session.rb', line 26

def [](key)
  @data[key.to_s]
end

#[]=(key, value) ⇒ Object



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

def []=(key, value)
  @data[key.to_s] = value
  @modified = true
end

#clearObject



40
41
42
43
# File 'lib/tina4/session.rb', line 40

def clear
  @data = {}
  @modified = true
end


60
61
62
# File 'lib/tina4/session.rb', line 60

def cookie_header
  "#{@options[:cookie_name]}=#{@id}; Path=/; HttpOnly; SameSite=Lax; Max-Age=#{@options[:max_age]}"
end

#delete(key) ⇒ Object



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

def delete(key)
  @data.delete(key.to_s)
  @modified = true
end

#destroyObject



55
56
57
58
# File 'lib/tina4/session.rb', line 55

def destroy
  @handler.destroy(@id)
  @data = {}
end

#saveObject



49
50
51
52
53
# File 'lib/tina4/session.rb', line 49

def save
  return unless @modified
  @handler.write(@id, @data)
  @modified = false
end

#to_hashObject



45
46
47
# File 'lib/tina4/session.rb', line 45

def to_hash
  @data.dup
end