The best Ruby CGI Sessions Tutorial In 2024, In this tutorial you can learn CGI :: Session class,
CGI :: Session can be saved as user and CGI environment persistent session state, after the sessions need to be closed, so you can ensure that data is written to the memory which, when the session is finished, you need to delete the data.
#!/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 { cgi.body ("bgcolor" => sess["bgcolor"]){ "The background of this page" + "changes based on the 'bgcolor'" + "each user has in session." + "Last access time: #{lastaccess}" } } }
Access "/cgi-bin/test.cgi?bgcolor=red" will jump to a specific page background color.
Session data exists in a temporary file directory on the server, prefix parameter specifies the prefix of the session, as a prefix for temporary files. On the server so that you can easily identify the different sessions temporary files.
CGI :: Session to maintain a persistent state of the user and the CGI environment. Session in memory can also be on the hard disk.
Ruby class Class CGI :: Session provides a simple way to create session:
CGI::Session::new( cgi[, option])
CGI enable a new session and returns the corresponding CGI :: Session object. Options may be optional hash, which can be the following values:
No. | Method Description |
---|---|
1 | [] Returns the key value. See examples. |
2 | [] = Sets the given key value. See examples. |
3 | delete Delete method calls the underlying database management. For FileStore, delete the physical file that contains the session. For MemoryStore, remove session data from memory. |
4 | update Call the update method of the underlying database management. For FileStore, the session is written to disk. For MemoryStore no effect. |