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

I cannot find simple examples for using Rack::Session::Cookie and would like to be able to store information in a cookie and access it on subsequent requests and expire.

These are the only examples I could find:

Here is what I get:

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

And then install / uninstall:

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

I cannot find any other guides or examples for setting this up. Can anyone help?

+6
source share
2 answers

You have already set a cookie in your question. I'm not sure if you mean something else by "tweaking".

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 that this did not work for you because you set an invalid domain. So I had to remove this from :domain => 'foo.com', BTW Sinatra wraps a rack cookie and provides a session assistant. So the above code worked fine for me. I believe the 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 the msg root session value or / by default 'not set', if you pass ?msg=someSTring , it should set msg with a new value.
  • access /sess to check what is happening in the session.

You can take some tips from How to set / get session vars in the Rack app?

+2
source

See an example below. This may give you a good idea.

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

0
source

Source: https://habr.com/ru/post/952073/


All Articles