加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在中间件中设置current_user?

发布时间:2020-12-17 04:33:45 所属栏目:百科 来源:网络整理
导读:为了提供更多我的问题的背景知识,请参阅这个 Github问题 – https://github.com/getsentry/raven-ruby/issues/144 我正在使用raven这是一个错误记录器.如果用户已登录,我想为current_user添加id.我收到的答案是 This should be done via your middleware or
为了提供更多我的问题的背景知识,请参阅这个 Github问题 – https://github.com/getsentry/raven-ruby/issues/144

我正在使用raven这是一个错误记录器.如果用户已登录,我想为current_user添加id.我收到的答案是

This should be done via your middleware or somewhere similar.

这意味着在Raven中设置current_user.

我读过关于中间件的内容,但仍然无法弄清楚如何将current_user放在一个中.

解决方法

对于Rails应用程序,我已成功在ApplicationController中的before_action中设置Raven(Sentry)上下文:
# 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读