Ruby/CGI/Session

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

sessions management

require "cgi"
require "cgi/session"
cgi = CGI.new("html3")
sess = CGI::Session.new(cgi,
"session_key" => "rubyweb",
"prefix" => "websession."
)
if sess["lastaccess"]
    msg = "You were last here #{sess["lastaccess"]}."
else
    msg = "you haven"t been here for a while"
end
count = (sess["accesscount"] || 0).to_i
count += 1
msg << "<p>Number of visits: #{count}"
sess["accesscount"] = count
sess["lastaccess"] = Time.now.to_s
sess.close 
cgi.out {
    cgi.html {
        cgi.body {
        msg
        }
    }
}



You can implement sessions on your Web site using Ruby

#! /ruby/bin/ruby
require "cgi"
require "cgi/session"
cgi = CGI.new("html3")
sessionKey = "yourKey"
sessionPrefix = "session."
session = CGI::Session.new(cgi, "session_key" => sessionKey,
                            "prefix"      => sessionPrefix)
$lastAccess = session["lastAccess"]
$visits     = session["visits"]
if $visits == nil
     $visits = 1
else
     $visits = $visits.to_i + 1
end
session["visits"] = $visits
session["lastAccess"] = "#{Time.now}"
cgi.out() do
    cgi.html do
        begin
            if $visits == 1
                "first visit!" +
            else
                "This is visit number #{$visits} this session." +
                "Your last access was at #{$lastAccess}<p>" +
                "The current time is #{Time.now}" +
            end
        end
    end
end