Ruby CGI Session
CGI::Session can save persistent session state for users and the CGI environment. A session needs to be closed after use so that data is written to storage; when the session is complete, you need to delete the data.
Example
!/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}
"
} } }
Accessing "/cgi-bin/test.cgi?bgcolor=red" will redirect to a page with the specified background color.
Session data is stored in the server's temporary file directory. The prefix parameter specifies the session prefix, which is used as the prefix for temporary files. This lets you easily identify different session temporary files on the server.
The CGI::Session class
CGI::Session maintains persistent state between a user and the CGI environment. A session can be in memory or on disk.
Class Methods
The Ruby class CGI::Session provides simple methods to create a session:
CGI
::
Session
::
new
(
cgi
[
,
option
]
)
Enables a new CGI session and returns the corresponding CGI::Session object. Options can be an optional hash with the following values:
- session_key: The key name for saving the session; defaults to _session_id.
- session_id: A unique session ID. Automatically generated.
- new_session: If true, creates a new session ID for the current session. If false, uses the existing session identifier via session_id. If this parameter is omitted, an existing session is used if available; otherwise a new one is created.
- database_manager: The class used to store sessions; can be CGI::Session::FileStore or CGI::Session::MemoryStore. Defaults to FileStore.
- tmpdir: For FileStore, the storage directory for the session.
- prefix: For FileStore, the prefix for session files.
Instance methods
| No. | Method Description |
|---|---|
| 1 | [ ] |
| Returns the value for the given key. See the example. | |
| 2 | [ ]= |
| Sets the value for the given key. See the example. | |
| 3 | delete |
| Calls the underlying database manager's delete method. For FileStore, deletes the physical file containing the session. For MemoryStore, removes the session data from memory. | |
| 4 | update |
| Calls the underlying database manager's update method. For FileStore, writes the session to disk. For MemoryStore, has no effect. |