Class: Web::Session

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

Overview

Purpose

Provides a file based implemetation of a session. This is hacked up from matz’s CGI::Session

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Session.



20
21
22
23
24
25
26
# File 'lib/web/session.rb', line 20

def initialize( cgi, options={} )
    @session_id = load_id( cgi, options )

    send_cookie( cgi, options[:session_key] || "_session_id" )

    @session = get_session_from_disk
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



78
79
80
81
# File 'lib/web/session.rb', line 78

def method_missing(method, *args, &block)
    # much faster than simple delegator
    @session.send(method,*args,&block)
end

Class Method Details

.create_idObject



10
11
12
13
14
15
16
17
# File 'lib/web/session.rb', line 10

def create_id
		md5 = Digest::MD5.new
		md5.update( String(Time.now.to_f) )
		md5.update( String(rand(0))  ) 
		#md5.update( String($$)       )
		#md5.update( 'thanks matz'    )
		md5.hexdigest[0,16]
end

Instance Method Details

#fileObject



69
70
71
# File 'lib/web/session.rb', line 69

def file
    File.expand_path(File.join(self.temp_dir, File.basename(@session_id.to_s).untaint))
end

#get_session_from_diskObject



28
29
30
31
32
33
34
35
36
# File 'lib/web/session.rb', line 28

def get_session_from_disk
    if File.exists? file
	File.open( file, "r" ) { |store|
	    Marshal.load store
	}
    else
	{}
    end
end

#load_id(cgi, options) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/web/session.rb', line 38

def load_id( cgi, options )
    if (options.has_key? :session_id)
	options[:session_id]
    elsif(cgi.cookies["_session_id"] && !cgi.cookies["_session_id"].empty?)
	cgi.cookies["_session_id"][0]
    else
	Session.create_id
    end
end

#resetObject

resets session to empty hash, for use in testing



74
75
76
# File 'lib/web/session.rb', line 74

def reset
    @session = {}
end

#saveObject

saves session to disk



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

def save
    File.open( file, "w+" ) { |store|
	Marshal.dump( @session, store )
    }
end


49
50
51
# File 'lib/web/session.rb', line 49

def send_cookie( cgi, session_key )
    cgi.set_cookie( session_key, @session_id )
end

#temp_dirObject



61
62
63
64
65
66
67
# File 'lib/web/session.rb', line 61

def temp_dir
  temp = ENV['TMP'] || ENV['TEMP'] || '/tmp'
  unless( File.exists? temp )
    temp = "c:/windows/temp"
  end
  temp
end