Dishcandanty
Dishcandanty

Reputation: 410

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

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?

Upvotes: 6

Views: 7877

Answers (2)

ch4nd4n
ch4nd4n

Reputation: 4197

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?

Upvotes: 2

Radhakrishna
Radhakrishna

Reputation: 698

Check the example below. It might give you good idea

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

Upvotes: 0

Related Questions