| Class | CGI::Session::FileStore |
| In: |
lib/cgi/session.rb
|
| Parent: | Object |
Create a new FileStore instance.
This constructor is used internally by CGI::Session. The user does not generally need to call it directly.
session is the session for which this instance is being created. The session id must only contain alphanumeric characters; automatically generated session ids observe this requirement.
option is a hash of options for the initializer. The following options are recognised:
| tmpdir: | the directory to use for storing the FileStore file. Defaults to Dir::tmpdir (generally "/tmp" on Unix systems). |
| prefix: | the prefix to add to the session id when generating the filename for this session‘s FileStore file. Defaults to the empty string. |
| suffix: | the prefix to add to the session id when generating the filename for this session‘s FileStore file. Defaults to the empty string. |
This session‘s FileStore file will be created if it does not exist, or opened if it does.
# File lib/cgi/session.rb, line 377
377: def initialize(session, option={})
378: dir = option['tmpdir'] || Dir::tmpdir
379: prefix = option['prefix'] || ''
380: suffix = option['suffix'] || ''
381: id = session.session_id
382: require 'digest/md5'
383: md5 = Digest::MD5.hexdigest(id)[0,16]
384: @path = dir+"/"+prefix+md5+suffix
385: if File::exist? @path
386: @hash = nil
387: else
388: unless session.new_session
389: raise CGI::Session::NoSession, "uninitialized session"
390: end
391: @hash = {}
392: end
393: end
Restore session state from the session‘s FileStore file.
Returns the session state as a hash.
# File lib/cgi/session.rb, line 398
398: def restore
399: unless @hash
400: @hash = {}
401: begin
402: lockf = File.open(@path+".lock", "r")
403: lockf.flock File::LOCK_SH
404: f = File.open(@path, 'r')
405: for line in f
406: line.chomp!
407: k, v = line.split('=',2)
408: @hash[CGI::unescape(k)] = CGI::unescape(v)
409: end
410: ensure
411: f.close unless f.nil?
412: lockf.close if lockf
413: end
414: end
415: @hash
416: end
Save session state to the session‘s FileStore file.
# File lib/cgi/session.rb, line 419
419: def update
420: return unless @hash
421: begin
422: lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600)
423: lockf.flock File::LOCK_EX
424: f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600)
425: for k,v in @hash
426: f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(v))
427: end
428: f.close
429: File.rename @path+".new", @path
430: ensure
431: f.close if f and !f.closed?
432: lockf.close if lockf
433: end
434: end