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