Session Access in Sinatra Middleware

I am working on a Sinatra project and set some variables in the session for later use.

The scenario for which I need help is that I want to access the session object in the middleware class. I use warden for authentication.

I want to do something similar below in the Middleware class:

class MyMiddleware def initialize(app, options={}) @app = app end def call(env) puts "#{session.inspect}" end end 

Is there any way to do this?

Thoughts?

+4
source share
1 answer

You cannot use the Sinatra session method in the Rack middleware, but you can access the session directly through the env hash.

Make sure the session middleware is in front of your middleware (so in Sinatra enable :sessions should be before use MyMiddleware ), then the session is accessible using the 'rack.session' key:

 class MyMiddleware def initialize(app, options={}) @app = app end def call(env) puts env['rack.session'].inspect @app.call(env) end end 

You might want to use the Rack::Request object to simplify access to the session and other parts of the env hash:

 def call(env) request = Rack::Request.new(env) puts request.session.inspect # other uses of request without needing to know what keys of env you need @app.call(env) end 
+8
source

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


All Articles