【问题标题】:How to access to 'current_user' outside of controller and model如何在控制器和模型之外访问“current_user”
【发布时间】:2017-12-01 12:33:58
【问题描述】:

我正在尝试访问控制器外部和模型外部的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

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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    如果引擎在同一个线程中运行,那么也许您可以将 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
    

    【讨论】:

      【解决方案2】:

      current_user 变量与当前请求相关联,因此与控制器实例相关联。在这种情况下,您可能应该只 parameterize your query 与您要过滤的用户:

      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)
      

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

      【讨论】:

      • 感谢您的回答。我的引擎没有任何控制器。请求通过 API 传递,然后使用 react 渲染
      【解决方案3】:

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

      这个blogpost的想法。

      基于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

      【讨论】:

        猜你喜欢
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多