Accessing session in Sinatra Middleware

≯℡__Kan透↙ 提交于 2019-12-06 04:21:51

问题


I am working on a Sinatra Project and have set some variables in the session for later usage.

The scenario for which I need help for is that I want to access the session object in a middleware class. I am using 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 a possibility for doing that?

Thoughts?


回答1:


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

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

class MyMiddleware
  def initialize(app, options={})
    @app = app
  end

  def call(env)
    puts env['rack.session'].inspect
    @app.call(env)
  end
end

You might prefer to use a Rack::Request object to make it easier to access 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


来源:https://stackoverflow.com/questions/9113162/accessing-session-in-sinatra-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!