1

You may have heard of Pundit. https://github.com/elabs/pundit Basically, it's an authorization gem.

What I want to know is, how does it access the variable current_user inside its classes?

I don't know how, but @user and user are both equal somehow to the 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. 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:

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. Please answer these two questions :)

Starkers
  • 10,273
  • 21
  • 95
  • 158

1 Answers1

0

The PostPolicy class doesn't query anything.

The authorize method is a controller instance method, so it can just call current_user. You've passed it @post, which it uses to determine which policy class to use. Then it creates a new instance of that class, passing current_user and @post through.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174