summaryrefslogtreecommitdiffstats
path: root/lib/zorglub/session.rb
blob: 583b142f282a7ed083242a97509723b0a21da50a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# -*- coding: UTF-8 -*-
#
require 'securerandom'
#
module Zorglub
    #
    class Node
        #
        def session
            @session ||= Session.new @request
        end
    end
    #
    class SessionHash
        #
        @data = {}
        class << self
            attr_reader :data
        end
        #
        def initialize sid
            @sid = sid
            # TODO if sid is nil, one should be created
            @session_data = SessionHash.data[sid]||={}
        end
        #
        def exists?
            not @sid.nil?
        end
        #
        def [] idx
            @session_data[idx]
        end
        #
        def []= idx, v
            @session_data[idx] = v
        end
    end
    #
    class Session
        #
        @session_key =  'zorglub.sid'
        @session_kls = Zorglub::SessionHash
        class << self
            attr_accessor :session_key, :session_kls
        end
        #
        def initialize req
            @request = req
            @instance = nil
        end
        #
        def setup!
            if Config.session_on
                @instance = Session.session_kls.new @request.cookies[Session.session_key]
            else
                @instance = {}
            end
        end
        private :setup!
        #
        def exists?
            setup! if @instance.nil?
            @instance.exists?
        end
        #
        def [] idx
            setup! if @instance.nil?
            @instance[idx]
        end
        #
        def []= idx, v
            setup! if @instance.nil?
            @instance[idx] = v
        end
        #
    end
    #
end
#
# EOF