Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby CGI Session

Ruby CGI Session

CGI::Session can save persistent session state for users and the CGI environment. A session needs to be closed after use so that data is written to storage; when the session is complete, you need to delete the data.

Example

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

"

} } }

Accessing "/cgi-bin/test.cgi?bgcolor=red" will redirect to a page with the specified background color.

Session data is stored in the server's temporary file directory. The prefix parameter specifies the session prefix, which is used as the prefix for temporary files. This lets you easily identify different session temporary files on the server.


The CGI::Session class

CGI::Session maintains persistent state between a user and the CGI environment. A session can be in memory or on disk.

Class Methods

The Ruby class CGI::Session provides simple methods to create a session:

CGI

::

Session

::

new

(

cgi

[

,

option

]

)

Enables a new CGI session and returns the corresponding CGI::Session object. Options can be an optional hash with the following values:

Instance methods

No. Method Description
1 [ ]
Returns the value for the given key. See the example.
2 [ ]=
Sets the value for the given key. See the example.
3 delete
Calls the underlying database manager's delete method. For FileStore, deletes the physical file containing the session. For MemoryStore, removes the session data from memory.
4 update
Calls the underlying database manager's update method. For FileStore, writes the session to disk. For MemoryStore, has no effect.