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 def initialize(session, option={}) dir = option['tmpdir'] || Dir::tmpdir prefix = option['prefix'] || '' suffix = option['suffix'] || '' id = session.session_id require 'digest/md5' md5 = Digest::MD5.hexdigest(id)[0,16] @path = dir+"/"+prefix+md5+suffix if File::exist? @path @hash = nil else unless session.new_session raise CGI::Session::NoSession, "uninitialized session" end @hash = {} end end
Restore session state from the session‘s FileStore file.
Returns the session state as a hash.
# File lib/cgi/session.rb, line 396 def restore unless @hash @hash = {} begin lockf = File.open(@path+".lock", "r") lockf.flock File::LOCK_SH f = File.open(@path, 'r') for line in f line.chomp! k, v = line.split('=',2) @hash[CGI::unescape(k)] = CGI::unescape(v) end ensure f.close unless f.nil? lockf.close if lockf end end @hash end
Save session state to the session‘s FileStore file.
# File lib/cgi/session.rb, line 417 def update return unless @hash begin lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600) lockf.flock File::LOCK_EX f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600) for k,v in @hash f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(v)) end f.close File.rename @path+".new", @path ensure f.close if f and !f.closed? lockf.close if lockf end end