Class: Syntropy::Session

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

Overview

A Session object serves as storage for data associated with the user’s browser session, such as flash data (for communicating notices and alerts). The session is modeled as a key-value store, where keys are strings, and values can be any value that can be represented in JSON, including arrays and hashes.

The session data is stored as an HTTP cookie.

Instance Method Summary collapse

Constructor Details

#initialize(request) ⇒ void

Initializes the session.

Parameters:



20
21
22
23
# File 'lib/syntropy/session.rb', line 20

def initialize(request)
  @request = request
  @data = nil
end

Instance Method Details

#[](key) ⇒ any

Returns the value associated with the given key.

Parameters:

  • key (String)

Returns:

  • (any)

    value



29
30
31
32
# File 'lib/syntropy/session.rb', line 29

def [](key)
  @data ||= load
  @data[key]
end

#[]=(key, value) ⇒ void

This method returns an undefined value.

Sets the value for the given key and updates the response session cookie.

Parameters:

  • key (String)
  • value (any)


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

def []=(key, value)
  @data ||= load
  @data[key] = value
  save(@data)
end

#delete(key) ⇒ any

Deletes the given key-value pair and updates the response session cookie.

Parameters:

  • key (String)

Returns:

  • (any)

    deleted value



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

def delete(key)
  @data ||= load
  value = @data.delete(key)
  save(@data.empty? ? nil : @data)
  value
end

#discardvoid

This method returns an undefined value.

Discards the session data, updating the response session cookie by emptying it.



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

def discard
  save(nil)
end

#flashSyntropy::Session::Flash

Returns the flash storage for the session.

Returns:

  • (Syntropy::Session::Flash)


67
68
69
70
# File 'lib/syntropy/session.rb', line 67

def flash
  @data ||= load
  @flash ||= Flash.new(self)
end