| 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 initialiser. 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 371
371: def initialize(session, option={})
372: dir = option['tmpdir'] || Dir::tmpdir
373: prefix = option['prefix'] || ''
374: suffix = option['suffix'] || ''
375: id = session.session_id
376: require 'digest/md5'
377: md5 = Digest::MD5.hexdigest(id)[0,16]
378: @path = dir+"/"+prefix+md5+suffix
379: if File::exist? @path
380: @hash = nil
381: else
382: unless session.new_session
383: raise CGI::Session::NoSession, "uninitialized session"
384: end
385: @hash = {}
386: end
387: end
Restore session state from the session‘s FileStore file.
Returns the session state as a hash.
# File lib/cgi/session.rb, line 392
392: def restore
393: unless @hash
394: @hash = {}
395: begin
396: lockf = File.open(@path+".lock", "r")
397: lockf.flock File::LOCK_SH
398: f = File.open(@path, 'r')
399: for line in f
400: line.chomp!
401: k, v = line.split('=',2)
402: @hash[CGI::unescape(k)] = CGI::unescape(v)
403: end
404: ensure
405: f.close unless f.nil?
406: lockf.close if lockf
407: end
408: end
409: @hash
410: end
Save session state to the session‘s FileStore file.
# File lib/cgi/session.rb, line 413
413: def update
414: return unless @hash
415: begin
416: lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600)
417: lockf.flock File::LOCK_EX
418: f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600)
419: for k,v in @hash
420: f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(v))
421: end
422: f.close
423: File.rename @path+".new", @path
424: ensure
425: f.close if f and !f.closed?
426: lockf.close if lockf
427: end
428: end