如何在中间件中设置current_user?

roh*_*hra 7 ruby-on-rails devise sentry

为了给我的问题提供更多背景信息,请参阅此Github问题 - https://github.com/getsentry/raven-ruby/issues/144

我正在使用raven哪个是错误记录器.我想为current_userif用户登录添加id .我收到的答案是

这应该通过您的中间件或类似的地方完成.

其中,这意味着在设定的乌鸦CURRENT_USER.

我读过关于中间件的内容,但仍然无法弄清楚如何才能进入中间件current_user.

Art*_*r N 15

对于Rails应用,我已经成功只设置在乌鸦(哨兵)上下文before_action中ApplicationController:

# application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_raven_context

  def set_raven_context
    # I use subdomains in my app, but you could leave this next line out if it's not relevant
    context = { account: request.subdomain }
    context.merge!({ user_id: current_user.id, email: current_user.email }) unless current_user.blank?
    Raven.user_context(context)
  end
end
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为乌鸦Rack中间件会在每次请求后清除上下文.看这里.但是,它可能不是最有效的,因为即使在大多数不会导致异常的情况下也要设置上下文.但无论如何,它并不是那么昂贵的操作,而且它会让你相当不需要注意新的Rack中间件或任何东西.


Roh*_*hit 1

我对此不太了解Raven,但下面是一种方法,使用它,我们可以在整个应用程序中通过请求访问当前用户。

我们创建了一个类,它充当缓存,并从当前线程插入/检索数据

class CustomCache
    def self.namespace
      "my_application"
    end

    def self.get(res)
      Thread.current[self.namespace] ||= {}
        val = Thread.current[self.namespace][res] 
        if val.nil? and block_given?
            val = yield
            self.set(res, val) unless val.nil?
        end
        return val
    end

    def self.set(key, value)
        Thread.current[self.namespace][key] = value
    end

    def self.reset
      Thread.current[self.namespace] = {}
    end
  end
Run Code Online (Sandbox Code Playgroud)

然后,当收到请求时,将检查当前会话,然后将用户的模型插入到缓存中,如下所示

def current_user
  if defined?(@current_user)
    return @current_user
  end
  @current_user = current_user_session && current_user_session.record
  CustomCache.set(:current_user, @current_user)
  return @current_user
end
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用以下代码从应用程序中的任何位置检索当前用户,

CustomCache.get(:current_user)
Run Code Online (Sandbox Code Playgroud)

我们还确保在请求被处理之前和之后重置缓存,所以我们这样做,

CustomCache.reset
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 这看起来很有趣。我想知道 Devise 是否有一个可以在中间件中使用的 current_user 方法。 (2认同)