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?
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 .
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.
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
msg
access root or /
defaults to 'not set' if you pass ?msg=someSTring
it should set msg with new value./sess
to check whats in session.You can take some cues from How do I set/get session vars in a Rack app?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With