Cookies by themselves still need a bit of work to be useful.
What
we really want is a
session: a persistent state for some Web
surfer. Sessions are handled with
CGI::Session
(documented beginning on page 504), which uses cookies
but provides a higher-level abstraction.
require "cgi"
require "cgi/session"
cgi = CGI.new("html3")
sess = CGI::Session.new( cgi, "session_key" => "rubyweb",
"session_id" => "9650",
"new_session" => true,
"prefix" => "web-session.")
sess["CustID"] = 123
sess["Part"] = "ABC"
cgi.out{
cgi.html{
"\nHTML content here"
}
}
|
This will send a cookie to the user named ``rubyweb'' with a value of
9650. It will also create a disk file in
$TMP/web-session.9650
with the
key, value pairs for
CustID
and
Part
.
When the user returns, all you need is a parameter to indicate the
session id. In this example, that would be
rubyweb=9650
. With
that value in the parameters, you'll be able to retrieve the full
set of saved session data.
require "cgi"
require "cgi/session"
cgi = CGI.new("html3")
sess = CGI::Session.new( cgi, "session_key" => "rubyweb",
"prefix" => "web-session.")
cgi.out{
cgi.html{
"\nCustomer #{sess['CustID']} orders an #{sess['Part']}"
}
}
|