Are there any basic examples of Rack::Session::Cookie usage?
Asked Answered
C

2

6

I can't find any simple examples for using Rack::Session::Cookie and would like to be able to store information in a cookie, and access it on later requests and have it expire.

These are the only examples I've been able to find:

Here's what I'm getting:

 use Rack::Session::Cookie, :key => 'rack.session',
                               :domain => 'foo.com',
                               :path => '/',
                               :expire_after => 2592000,
                               :secret => 'change_me'

And then setting/retrieving:

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

I can't find any other guides or examples for the setup of this. Can someone help?

Cuirass answered 20/8, 2013 at 3:52 Comment(0)
N
2

You have already setup cookie in your question. I am not sure if you means something else by "setup".

Instead of env['rack.session'] you can use session[KEY] for simplification.

session[:key] = "vaue" # will set the value
session[:key] # will return the value

Simple Sinatra example

require 'sinatra'
set :sessions, true
get '/' do
    session[:key_set] = "set"
    "Hello"
end
get "/sess" do
    session[:key_set]
end

Update

I believe it wasn't working for you because you had set invalid domain. So I had to strip that off :domain => 'foo.com',. BTW Sinatra wraps Rack cookie and exposes session helper. So above code worked fine for me. I believe following code should work as expected.

require 'sinatra'
use Rack::Session::Cookie, :key => 'rack.session',
  :expire_after => 2592000,
  :secret => 'change_me'
get '/' do
  msg = params["msg"] || "not set"
  env["rack.session"][:msg] = msg
  "Hello"
end
get "/sess" do
  request.session["msg"]
end
  • set session value msg access root or / defaults to 'not set' if you pass ?msg=someSTring it should set msg with new value.
  • access /sess to check whats in session.

You can take some cues from How do I set/get session vars in a Rack app?

Nambypamby answered 20/8, 2013 at 6:59 Comment(3)
The issue I have discovered with this is if I restart the Web Service, the session is dead, and the set Session isn't saved in the cookie. So if you hit '/', restart sinatra, then hit /sess, you'll not return any information.Cuirass
Note that above code is for Sinatra and it is slightly different from the code snippet you have posted but basically it wraps Rack Cookie internally AFAIK. I haven't worked on Rack directly so I had to spend some time to figure this out. Please refer to updated answer above.Nambypamby
I think you should clarify the difference between env["rack.session"][:msg] and request.session["msg"].Harrier
S
0

Check the example below. It might give you good idea

http://chneukirchen.org/repos/rack/lib/rack/session/cookie.rb

Shoat answered 20/8, 2013 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.