Module: SessionVars

Defined in:
documented/sessionvars.rb

Overview

New module for managing session variables This module provides a way to store variables needed by more than one script without saving them to the sqlite database.

Examples:

Setting a session variable

SessionVars["user_id"] = 42

Retrieving a session variable

user_id = SessionVars["user_id"]

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:

Retrieving a session variable

value = SessionVars["key"]

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.



19
20
21
# File 'documented/sessionvars.rb', line 19

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

.[]=(name, val) ⇒ Object

Sets the value of a session variable by name.

Examples:

Setting a session variable

SessionVars["key"] = "value"

Parameters:

  • name (String)

    The name of the session variable to set.

  • val (Object, nil)

    The value to set for the session variable. If nil, the variable will be deleted.

Returns:

  • (Object)

    The value that was set.



29
30
31
32
33
34
35
# File 'documented/sessionvars.rb', line 29

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:

Listing all session variables

all_vars = SessionVars.list

Returns:

  • (Hash)

    A hash containing all session variables.



41
42
43
# File 'documented/sessionvars.rb', line 41

def SessionVars.list
  @@svars.dup
end

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

Handles dynamic method calls for setting and getting session variables.

Examples:

Using dynamic methods

SessionVars.some_var = "value"
value = SessionVars.some_var

Parameters:

  • arg1 (Symbol, String)

    The name of the session variable or the method being called.

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

    The value to set if the method is a setter (ends with ‘=’), otherwise ignored.

Returns:

  • (Object, nil)

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



52
53
54
55
56
57
58
59
60
61
62
# File 'documented/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