Latest web development tutorials

Ruby CGI Sessions

CGI :: Session can be saved as user and CGI environment persistent session state, after the sessions need to be closed, so you can ensure that data is written to the memory which, when the session is finished, you need to delete the data.

#!/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}"
    }
  }
}

Access "/cgi-bin/test.cgi?bgcolor=red" will jump to a specific page background color.

Session data exists in a temporary file directory on the server, prefix parameter specifies the prefix of the session, as a prefix for temporary files. On the server so that you can easily identify the different sessions temporary files.


CGI :: Session class

CGI :: Session to maintain a persistent state of the user and the CGI environment. Session in memory can also be on the hard disk.

Class methods

Ruby class Class CGI :: Session provides a simple way to create session:

CGI::Session::new( cgi[, option])

CGI enable a new session and returns the corresponding CGI :: Session object. Options may be optional hash, which can be the following values:

  • session_key: Save session keys by default _session_id.
  • session_id: unique session ID.Automatic generated
  • new_session: If you create a new Session id for the current session is true.If false, by using the existing session session_id identity. If omitted, if available, use an existing session, or the creation of a new one.
  • database_manager: Save sessions for classes, may be CGI :: Session :: FileStore or CGI :: Session :: MemoryStore.The default is FileStore.
  • tmpdir: For FileStore, a session fault storage directory.
  • prefix: For FileStore, a session file prefix.

Examples of methods

No. Method Description
1 []
Returns the key value. See examples.
2 [] =
Sets the given key value. See examples.
3 delete
Delete method calls the underlying database management. For FileStore, delete the physical file that contains the session. For MemoryStore, remove session data from memory.
4 update
Call the update method of the underlying database management. For FileStore, the session is written to disk. For MemoryStore no effect.