Database Reference
In-Depth Information
require "cgi"
require "cgi/session"
require "mysqlstore"
To create a session, first create a CGI object. Then invoke CGI::Session.new , which
takes several arguments. The first is a CGI object associated with the script; it must exist
before you can open the session. Other arguments provide information about the ses‐
sion itself. Those following are relevant no matter which storage manager you use:
session_key
The session key is the name of the cookie to send to the client. The default key value
is _session_key ; we'll use RUBYSESSID .
new_session
This argument is true to force a new session to be created, or false to use an existing
session, which is assumed to have already been created during a previous request.
It's also possible to create a session if it does not exist and use the current session if
it does. To enable that behavior, omit the new_session argument; our example script
does so.
database_manager
The name of the class that provides storage management for session records. If this
argument is omitted, the session manager uses temporary files.
To use the mysql-session package as the storage manager, the database_manager
argument should be CGI::Session::MySQLStore . In that case, mysql-session enables
several other arguments for the CGI::Session.new method. You can pass in arguments
that instruct the session manager to establish its own connection to MySQL, or open
your own connection and pass its database handle to the session manager.
The following discussion shows both approaches, but either way, we need a table for
storing session records. For mysql-session , create a table named ruby_session with
the following structure:
CREATE TABLE ruby_session
(
session_id VARCHAR ( 255 ) NOT NULL ,
session_value LONGBLOB NOT NULL ,
update_time DATETIME NOT NULL ,
PRIMARY KEY ( session_id )
);
To have the session manager open its own connection to MySQL, create the session like
this:
cgi = CGI . new ( "html4" )
sess_id = cgi . cookies [ "RUBYSESSID" ]
session = CGI : :Session . new (
cgi ,
"session_key" => "RUBYSESSID" ,
Search WWH ::




Custom Search