Copyright © tutorialspoint.com

Ruby CGI Cookies

previous next


HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user regitration ends after completing many pages. But how to maintain user's session information across all the web pages.

In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

How It Works

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.

Cookies are a plain text data record of 5 variable-length fields:

Handling Cookies in Ruby

You can create a named cookie object and store a any textual information in it. To send it down to the browser, set a cookie header in the call to CGI.out.

#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cookie = CGI::Cookie.new('name' => 'mycookie',
                         'value' => 'Zara Ali',
                         'expires' => Time.now + 3600)
cgi.out('cookie' => cookie) do
   cgi.head + cgi.body { "Cookie stored" }
end

The next time the user comes back to this page, you can retrieve the cookie values set as shown below:

#!/usr/bin/ruby

require "cgi"
cgi = CGI.new("html4")
cookie = cgi.cookies['mycookie']
cgi.out('cookie' => cookie) do
   cgi.head + cgi.body { "Flavor: " + cookie[0] }
end

Cookies are represented using a separate object of class CGI::Cookie, containing the following accessors:

AttributeReturned Value
nameCookie name
valueAn array of cookie values
pathThe cookie's path
domainThe domain
expiresThe expiration time (as a Time object)
secureTrue if secure cookie

previous

Copyright © tutorialspoint.com