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?

Community
  • 1
  • 1
Dishcandanty
  • 411
  • 1
  • 6
  • 13

2 Answers2

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?

Community
  • 1
  • 1
ch4nd4n
  • 4,110
  • 2
  • 21
  • 43
  • 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. – Dishcandanty Aug 20 '13 at 15:27
  • 1
    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. – ch4nd4n Aug 21 '13 at 05:42
  • I think you should clarify the difference between `env["rack.session"][:msg]` and `request.session["msg"]`. – Redoman Oct 07 '15 at 15:54
0

Check the example below. It might give you good idea

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

Radhakrishna
  • 698
  • 1
  • 7
  • 22