简体   繁体   English

从gem访问current_user

[英]Access current_user from a gem

You may have heard of Pundit. 您可能听说过Pundit。 https://github.com/elabs/pundit Basically, it's an authorization gem. https://github.com/elabs/pundit基本上,这是一个授权工具。

What I want to know is, how does it access the variable current_user inside its classes? 我想知道的是,它如何访问其类中的变量current_user

I don't know how, but @user and user are both equal somehow to the current_user 我不知道如何,但是@useruser在某种程度上都等于current_user

class PostPolicy
  attr_reader :user, :post

  def initialize(user, post)
    @user = user
    @post = post
  end

  def update?
    user.admin? or not post.published?
  end
end

We also have the post variable inside this class. 我们在这个类中也有post变量。 We can access this by running 我们可以通过运行来访问它

def publish
  @post = Post.find(params[:id])
  authorize @post
end

in an action. 在行动中。

To install Pundit you need to include the module to the application controller: 要安装Pundit,您需要将该模块包含在应用程序控制器中:

class ApplicationController < ActionController::Base
    include Pundit
end

However, I still can't see how the class "queries" the controller for the current_user and how authorize gives the variable (post) to the class. 但是,我仍然看不到该类如何“查询” current_user的控制器,以及如何授权将变量(post)提供给该类。 Please answer these two questions :) 请回答这两个问题:)

The PostPolicy class doesn't query anything. PostPolicy类不查询任何内容。

The authorize method is a controller instance method, so it can just call current_user . authorize方法是一个控制器实例方法,因此它只能调用current_user You've passed it @post , which it uses to determine which policy class to use. 您已经传递了@post ,它用于确定要使用的策略类。 Then it creates a new instance of that class, passing current_user and @post through. 然后,它创建该类的新实例,并传递current_user@post

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

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