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