Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • How do I set/get session vars in a Rack app?
  • http://rack.rubyforge.org/doc/classes/Rack/Session/Cookie.html

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?

like image 834
Dishcandanty Avatar asked Aug 20 '13 03:08

Dishcandanty


People also ask

What is rack session cookie?

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 .

Where are session cookies used?

Session cookies allow websites to remember users within a website when they move between web pages. These cookies tell the server what pages to show the user so the user doesn't have to remember where they left off or start navigating the site all over again. Therefore, without session cookies, websites have no memory.


1 Answers

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?

like image 106
ch4nd4n Avatar answered Oct 01 '22 22:10

ch4nd4n