Page Content

Tutorials

What Is Cookies And Sessions In Ruby, key Differences Of It

Cookies and Sessions in Ruby

Sessions & Cookies in Web Apps is a crucial subject to comprehend how web apps follow user activity and preserve continuity despite the HTTP protocol’s intrinsic statelessness. Sessions and cookies are both tools for handling a visitor’s persistent data. This is an overview of sessions and cookies with an emphasis on how they are used in web applications, specifically in relation to the Ruby on Rails framework and Ruby’s CGI module.

What is Cookies in Ruby?

Cookies allow web programs to store state data directly on the user’s computer. Small cookie files are used to store all cookie data on the visitor’s machine. A cookie is a transient local file that stores information about a user and retains that information until it is manually erased, expires, or the session has finished. In order to serialize these files into key-value pairs (hashes) and store them in a session, Ruby on Rails parses cookies.

Key Characteristics of Cookies

Storage: Data is kept on the client side.

Capacity: A maximum of four kilobytes of data can be stored in a cookie.

Data Type: While Rails can automatically transform some variables, a cookie can only store string values.

Security: If sensitive or private data is saved in a cookie, it may be intercepted unless SSL (HTTPS) is used to encrypt all client requests. The sensitive data may still be accessible through cross-site scripting attacks.

Use Cases: Cookies are helpful when you don’t want to save session information on your server, the data isn’t important, and it’s not particularly big.

You can also read What Is Command Line Applications In Ruby With Examples

Setting and Retrieving Cookies (Ruby CGI)

The loading and saving of cookies is managed by the Ruby CGI class. Using the CGI#cookies method, you can retrieve cookies related to the active request. By providing a cookie object or an array of cookies using the cookie parameter of the CGI#out method, you can set cookies back to the browser.

The standard way for setting cookies is CGI::Cookie.new. You can set an expiration time when setting a cookie.

Code Example 1: Setting and Retrieving a Cookie via CGI

By checking for cookies, incrementing a counter (hits), and setting a new cookie value, this example demonstrates how a CGI script can refresh the page every two seconds (Refresh: 2).

File: headers.cgi (Partial)
require "cgi"
cgi = CGI.new("html3")
# Retrieve or create the "rubycookbook" cookie
cookie = cgi.cookies['rubycookbook']
cookie = CGI::Cookie.new(‘rubycookbook’, ‘hits=0’, “last=#{Time.now}”) if cookie.empty?
# Read and increment hits
hits = cookie.value.split('=')
cookie.value = "hits=#{hits.succ}"
cookie.value = "last=#{Time.now}"
# Create hash of headers, including the cookie, and output HTML
header = { ‘status’ => ‘OK’, ‘cookie’ => [cookie], ‘Refresh’ => 2 }
cgi.out(header) do
cgi.html('PRETTY' => ' ') do
# ... HTML body outputting hits and last visit time
end
end

Setting and Retrieving Cookies (Ruby on Rails)

A method named cookies in Rails is available to controllers, helpers, and mailers (but usually not views) and returns a hash of the HTTP cookies of the current client.

Code Example 2: Counting Visits with a Rails Cookie

To set a cookie in Rails, simply enter a key/value pair in the cookies hash.

class ApplicationController
  def initialize(cookies = {})
    @cookies = cookies
    count_visits
  end

  def count_visits
    value = (@cookies[:visits] || 0).to_i
    @cookies[:visits] = value + 1
    @visits = @cookies[:visits]
  end

  attr_reader :visits, :cookies
end

# Test it
c = ApplicationController.new
puts c.visits

Output

1

If you need more control, such as setting an expiration time (cookies expire by default when the browser closes), you pass a hash to the cookies method: cookies[:key] = { :value => '123', :expires => Time.now + 1.hour}.

You can also read What Is Automated Testing for Web Applications In Ruby

What is Sessions in Ruby?

Usually based on cookies, sessions are a higher-level abstraction intended to preserve persistent state for web users. A mechanism to store data associated with a specific user’s interaction with the application, typically for the duration of their visit.

Key Characteristics of Sessions

Storage: The server houses the vast majority of the session data. The only thing the client keeps is a little session cookie with a unique ID (a key) that connects to the information on the server.

Security: Sessions protect sensitive information better than client-side cookies because personal information is not saved on the visitor’s machine.

Capacity: Sessions surpass the 4KB cookie data limit.

Use Cases: Sessions are usually preferable over cookies, especially when handling sensitive or substantial data. Sessions may remain in a persistent state for the duration of the user’s visit, spanning numerous actions.

You can also read Web Application Frameworks In Ruby: Power Of Ruby On Rails

Setting and Retrieving Session Information (Ruby on Rails)

The session method is a way to retrieve the server-side session hash in a Rails application (in controllers, views, helpers, and mailers). This hash’s contents are persistent between queries made from the same web browser.

Code Example 3: Tracking User Login with Rails Session

When authentication is successful, the user’s ID is stored in a session hash in a login system.

class UserController < ApplicationController
  def process_login
    if (user = User.authenticate(params[:user]))
      session[:id] = user.id
      redirect_to session[:return_to] || root_path
    else
      flash[:error] = "Invalid login"
      render :login
    end
  end

  def set_user
    @user = User.find(session[:id]) if session[:id]
  end
end

Session Storage Mechanisms (Rails)

By default, PStore, which serialises data using Marshal to temporary files on the server, is used by Rails to store sessions. Although there are options for high-traffic or multi-server deployments, this works well for tiny sites:

ActiveRecordStore: keeps session data in a table in the database.

DRbStore / MemCacheStore: For speed and dissemination, it generates an in-memory hash that is reachable across the network.

What is the difference between a cookie and a session?

Cookies can be thought of as small, standalone messages that are pinned to your home’s front door (the client’s browser). You don’t need a host to keep track of them, but anyone walking by can read them and you can only fit a little amount of information on them.

On the contrary, a session is comparable to receiving a gym locker key. Until you return, all of your valuables (the session data) are safely kept in a secure locker (the server), allowing for much more data and improved security. The key (the session cookie on the browser) is little and notifies the system who you are.

You can also read Building Your First Website Sinatra In Ruby With Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index