繁体   English   中英

如何在控制器和模型外部访问“ current_user”

[英]How to access to 'current_user' outside of controller and model

我正在尝试访问控制器外部和模型外部的current user 这是项目的架构

main_engine
|_bin
|_config
|_blorgh_engine
    |_ —> this where devise is installed
|
|_ blorgh2_engine
    |_app
        |_assets
        |_models
        |_assets
        |_queries
            |_ filter_comments.rb -> Where I want to use current_user

 module Blorgh2
    # A class used to find comments for a commentable resource
    class FilterComments < Rectify::Query
      # How to get current_user here ?
    ...
    end
 end

我认为没有办法做到这一点。 如果您有想法,欢迎您。

current_user变量与当前请求绑定,因此与控制器实例绑定。 在这种情况下,您应该只使用要过滤的用户对查询进行参数化

class FilterComments < Rectify::Query
  def initialize(user)
    @user = user
  end

  def query
    # Query that can access user
  end
end

然后,在您的控制器中:

filtered_comments = FilterComments.new(current_user)

这可以弄清楚它的来源,允许您对任何用户重用它,并使查询对象可测试,因为您可以在测试设置中传入任何用户。

如果引擎在同一线程中运行,那么您可以将current_user存储在该线程中。

class ApplicationController < ActionController::Base

  around_action :store_current_user

  def store_current_user
    Thread.current[:current_user] = current_user
    yield
    ensure
    Thread.current[:current_user] = nil
  end

end

然后在您的filter_comments.rb可以定义一个方法

def current_user
  Thread.current[:current_user]
end

在我的应用中,我使用的变量范围仅限于当前正在执行的线程。 这是Rails 5的功能,它确实有助于解决这种超出范围的情况。

这个博客文章中的想法。

基于Module#thread_mattr_accessor的实现

这里是代码示例。

class AuthZoneController < ApplicationController
  include Current

  before_action :authenticate_user
  around_action :set_current_user

  private

  def set_current_user
    Current.user = current_user
    yield
  ensure
    # to address the thread variable leak issues in Puma/Thin webserver
    Current.user = nil
  end

end


# /app/controllers/concerns/current.rb
module Current
  thread_mattr_accessor :user
end

现在,您可以在所有应用程序范围内的当前线程中访问Current.user

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM