May 12, 2021 Ruby
CGI:: Session can save a persistent session state for the user and the CGI environment, and the session needs to be closed after use, which ensures that the data is written to the store and that you need to delete the data when the session is complete.
#!/usr/bin/ruby require 'cgi' require 'cgi/session' cgi = CGI.new("html4") sess = CGI::Session.new( cgi, "session_key" => "a_test", "prefix" => "rubysess.") lastaccess = sess["lastaccess"].to_s sess["lastaccess"] = Time.now if cgi['bgcolor'][0] =~ /[a-z]/ sess["bgcolor"] = cgi['bgcolor'] end cgi.out{ cgi.html { cgi.body ("bgcolor" => sess["bgcolor"]){ "The background of this page" + "changes based on the 'bgcolor'" + "each user has in session." + "Last access time: #{lastaccess}" } } }
Visit "/cgi-bin/test.cgi?bgcolor-red" to jump to the page that specifies the background color.
Session data exists in the server's temporary file directory, and the prefix parameter specifies the prefix of the session as the prefix of the temporary file. This makes it easy for you to identify different session temporary files on the server.
CGI:: Session maintains the persistence of the user and the CGI environment. S essions can be in memory or on a hard disk.
Ruby Class CGI::Session provides an easy way to create sessions:
CGI::Session::new( cgi[, option])
Enable a new CGI session and return the appropriate CGI::Session object. T he option can be an optional hash, which can be the following value:
Serial number | Method description |
---|---|
1 |
[ ]
Returns the value of the given key. View the instance. |
2 |
[ ]=
Sets the value of a given key. View the instance. |
3 |
delete
Calls the deletion method for the underlying database management. F or FileStore, delete the physical file that contains the session. For MemoryStore, the session data is removed from memory. |
4 |
update
Call the update method for the underlying database management. F or fileStore, write the session to disk. N o effect on MemoryStore. |