1 # cgi/session/memcached.rb - persistent storage of marshalled session data
5 # This file provides the CGI::Session::MemCache class, which builds
6 # persistence of storage data on top of the MemCache library. See
7 # cgi/session.rb for more details on session storage managers.
12 require_library_or_gem
'memcache'
16 # MemCache-based session storage class.
18 # This builds upon the top-level MemCache class provided by the
19 # library file memcache.rb. Session data is marshalled and stored
20 # in a memcached cache.
22 def check_id(id
) #:nodoc:#
23 /[^0-9a-zA-Z]+/ =~ id
.to_s
? false : true
26 # Create a new CGI::Session::MemCache instance
28 # This constructor is used internally by CGI::Session. The
29 # user does not generally need to call it directly.
31 # +session+ is the session for which this instance is being
32 # created. The session id must only contain alphanumeric
33 # characters; automatically generated session ids observe
36 # +options+ is a hash of options for the initializer. The
37 # following options are recognized:
39 # cache:: an instance of a MemCache client to use as the
42 # expires:: an expiry time value to use for session entries in
43 # the session cache. +expires+ is interpreted in seconds
44 # relative to the current time if it\92s less than 60*60*24*30
45 # (30 days), or as an absolute Unix time (e.g., Time#to_i) if
46 # greater. If +expires+ is +0+, or not passed on +options+,
47 # the entry will never expire.
49 # This session's memcache entry will be created if it does
50 # not exist, or retrieved if it does.
51 def initialize(session
, options
= {})
52 id
= session
.session_id
54 raise ArgumentError
, "session_id '%s' is invalid" % id
56 @cache = options
['cache'] || MemCache
.new('localhost')
57 @expires = options
['expires'] || 0
58 @session_key = "session:#{id}"
60 # Add this key to the store if haven't done so yet
61 unless @cache.get(@session_key)
62 @cache.add(@session_key, @session_data, @expires)
66 # Restore session state from the session's memcache entry.
68 # Returns the session state as a hash.
70 @session_data = @cache[@session_key] || {}
73 # Save session state to the session's memcache entry.
75 @cache.set(@session_key, @session_data, @expires)
78 # Update and close the session's memcache entry.
83 # Delete the session's memcache entry.
85 @cache.delete(@session_key)
97 # MemCache wasn't available so neither can the store be