Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

2. Fundamentals > Sessions

Sessions

Although HTTP is itself a stateless protocol, one way to maintain the state for a user is through the use of cookie-based sessions, demonstrated in Example 2-33. In this approach, a cookie (in this case, one named rack.session) is stored client-side and used to house data related to the activity in the current user’s session.

Note

A more thorough discussion of cookies in general is up next.

You can enable sessions via the configure block. Once enabled, the session object can be used to store and retrieve values.

Example 2-33. Using cookie-based session management

require 'sinatra'

configure do
  enable :sessions
end

before do
  content_type :txt
end

get '/set' do
  session[:foo] = Time.now
  "Session value set."
end

get '/fetch' do
  "Session value: #{session[:foo]}"
end

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial