Module: SessionVars

Defined in:
lib/sessionvars.rb

Overview

A module to manage session variables that are not persisted in a database.

Constant Summary collapse

@@svars =
Hash.new

Class Method Summary collapse

Class Method Details

.[](name) ⇒ Object?

Retrieves the value of a session variable by name.

Examples:

SessionVars[:user_id] # => 123

Parameters:

  • name (String)

    the name of the session variable to retrieve.

Returns:

  • (Object, nil)

    the value of the session variable, or nil if it does not exist.



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

def SessionVars.[](name)
  @@svars[name]
end

.[]=(name, val) ⇒ void

This method returns an undefined value.

Sets the value of a session variable by name.

Examples:

SessionVars[:user_id] = 123

Parameters:

  • name (String)

    the name of the session variable to set.

  • val (Object, nil)

    the value to assign to the session variable; if nil, the variable is deleted.



26
27
28
29
30
31
32
# File 'lib/sessionvars.rb', line 26

def SessionVars.[]=(name, val)
  if val.nil?
    @@svars.delete(name)
  else
    @@svars[name] = val
  end
end

.listHash

Returns a duplicate of the current session variables.

Examples:

SessionVars.list # => { user_id: 123 }

Returns:

  • (Hash)

    a duplicate of the session variables hash.



39
40
41
# File 'lib/sessionvars.rb', line 39

def SessionVars.list
  @@svars.dup
end

.method_missing(arg1, arg2 = '') ⇒ Object?

Note:

This method allows for dynamic access to session variables using method names.

Handles dynamic method calls for setting and getting session variables.

Examples:

SessionVars.user_id = 123
SessionVars.user_id # => 123

Parameters:

  • arg1 (Symbol, String)

    the name of the session variable or a setter method (ending with ‘=’).

  • arg2 (Object, nil) (defaults to: '')

    the value to assign if setting a variable; ignored if getting a variable.

Returns:

  • (Object, nil)

    the value of the session variable if getting, or nil if deleted.



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/sessionvars.rb', line 52

def SessionVars.method_missing(arg1, arg2 = '')
  if arg1[-1, 1] == '='
    if arg2.nil?
      @@svars.delete(arg1.to_s.chop)
    else
      @@svars[arg1.to_s.chop] = arg2
    end
  else
    @@svars[arg1.to_s]
  end
end