How to use sinatra session
Asked Answered
C

2

9
enable :sessions
get '/foo' do
  session['m'] = 'Hello World!'
  redirect '/bar'
end

get '/bar' do
  session['m']   # => 'Hello World!'

end

It does not seem to work.

Civilly answered 17/4, 2011 at 12:33 Comment(1)
it works. what is your ruby and sinatra version?Tripos
V
15

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.

Venola answered 19/4, 2011 at 9:32 Comment(3)
Thanks, yes I use shotgun. Could you give a guide with more details?Civilly
I had the same issue using Shotgun, just upgraded to sinatra-1.2.6 and it works as expected with Shotgun.Incommensurate
rerun is an alternative to shotgun. gem install rerun then start your app with rerun ruby app.rbPelagias
R
13

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

Here's my test app:

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

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
    nil

phrogz$ 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.

Rubicund answered 17/4, 2011 at 13:22 Comment(3)
Really thanks, your method is really cool. The cause is I use shotgun server.Civilly
@Civilly I'm glad this helped. If you feel that this solved your problem, you should accept it as the answer (press the checkmark next to the answer). If @Konstantin's answer has solved your problem, mark it as accepted.Rubicund
helpful, but not the final solution.Civilly

© 2022 - 2024 — McMap. All rights reserved.