Database Reference
In-Depth Information
1. After opening the session, extract values from the session and convert them from
“generic” string form to properly typed values.
2. Work with the typed values until it is time to close the session.
3. Convert the typed values to string form, store them in the session, and close it.
The following script uses the CGI::Session session manager to track the number of
requests in a session and the time of each request. After 10 requests, the script deletes
the session to cause a new session to begin for the next request:
#!/usr/bin/ruby -w
# sess_track.rb: session request counting/timestamping demonstration
require "Cookbook"
require "cgi"
require "cgi/session"
require "mysqlstore"
title = "Ruby Session Tracker" ;
dbh = Cookbook : :connect
cgi = CGI . new ( "html4" )
session = CGI : :Session . new (
cgi ,
"session_key" => "RUBYSESSID" ,
"database_manager" => CGI : :Session :: MySQLStore ,
"db.dbh" => dbh ,
"db.name" => "cookbook" ,
"db.table" => "ruby_session"
)
# extract string values from session, convert them to the proper types
count = session [ "count" ]
count = ( count . nil? ? 0 : count . to_i )
timestamp = session [ "timestamp" ]
timestamp = ( timestamp . nil? ? [] : timestamp . split ( "," ))
# increment counter and add current timestamp to timestamp array
count = count + 1
timestamp << Time . now () . strftime ( "%Y-%m-%d %H:%M:%S" )
# construct content of page body
page = ""
page << cgi . p { "This session has been active for #{ count } requests." }
page << cgi . p { "The requests occurred at these times:" }
page << cgi . ol { timestamp . collect { | t | cgi . li { t . to_s } } }
Search WWH ::




Custom Search