How to use sinatra session How to use sinatra session ruby ruby

How to use sinatra session


Are you using shotgun? If so, do the following:

configure(:development) { set :session_secret, "something" }

This will no longer be necessary in Sinatra 1.3.


Perhaps you have cookies disabled on your web browser? Sinatra's sessions use cookies by default.

Here's my test app:

require 'sinatra'enable :sessionsget '/foo' do  session['m'] = 'Hello World!'  redirect '/bar'endget '/bar' do  <<-ENDRESPONSE    Ruby:    #{RUBY_VERSION}    Rack:    #{Rack::VERSION}    Sinatra: #{Sinatra::VERSION}    #{session['m'].inspect}  ENDRESPONSEend

And here it is in action:

phrogz$ curl --cookie-jar cookies.txt -L http://localhost:4567/foo    Ruby:    1.9.2    Rack:    [1, 1]    Sinatra: 1.2.3    "Hello World!"phrogz$ curl -L http://localhost:4567/foo    Ruby:    1.9.2    Rack:    [1, 1]    Sinatra: 1.2.3    nilphrogz$ cat cookies.txt # Netscape HTTP Cookie File# http://curl.haxx.se/rfc/cookie_spec.html# This file was generated by libcurl! Edit at your own risk.localhost   FALSE   /   FALSE   0   rack.session    BAh7BkkiBm0GOgZFRkkiEUhl...

Without cookies, your redirect will work but it will be as though it's a brand new session after the redirect, with the session starting from scratch.