Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set/get session vars in a Rack app?

Tags:

ruby

session

rack

use Rack::Session::Pool
...
session[:msg]="Hello Rack"

EDIT: The word session doesn't seem to resolve. I included the Session pool middleware in my config.ru, and try to set a variable in an ERB file (I'm using Ruby Serve) and it complains "undefined local variable or method `session'"

Thanks!

like image 918
Sunder Avatar asked May 04 '12 15:05

Sunder


People also ask

What is rack session?

Rack::Session::Cookie provides simple cookie based session management. By default, the session is a Ruby Hash stored as base64 encoded marshalled data set to :key (default: rack. session). The object that encodes the session data is configurable and must respond to encode and decode .


1 Answers

session is a method that is part of some web frameworks, for example Sinatra and Rails both have session methods. Plain rack applications don’t have a session method, unless you add one yourself.

The session hash is stored in the rack env hash under the key rack.session, so you can access it like this (assuming you’ve named the rack environment to your app env):

env['rack.session'][:msg]="Hello Rack"

Alternatively, you could use Rack’s built in request object, like this:

request = Rack::Request.new(env)
request.session[:msg]="Hello Rack"
like image 58
matt Avatar answered Oct 22 '22 23:10

matt