Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

pundit

> 编程语言
Open source

Minimal authorization through OO design and pure Ruby classes

8.5K stars0 likes4 views
WebsiteGitHub

About

Minimal authorization through OO design and pure Ruby classes

Pundit

Pundit provides a set of helpers which guide you in leveraging regular Ruby classes and object oriented design patterns to build a straightforward, robust, and scalable authorization system.

Links:

  • API documentation for the most recent version
  • Source Code
  • Contributing
  • Code of Conduct

Maintained by Varvet

Pundit is built and maintained by Varvet, a digital product studio in Sweden. Jonas Nicklas first released it in 2012, and Varvet has kept it small and sharp ever since: one tool that does one thing well. Over 100 million downloads, used by 38,000+ repositories on GitHub.

It started as a pattern we wrote up in Simple authorization in Ruby on Rails apps. We build Ruby on Rails products from our studio in Sweden. If you want the team behind Pundit in the room, we're at varvet.com.

Installation

Please note that the README on GitHub is accurate with the latest code on GitHub. You are most likely using a released version of Pundit, so please refer to the documentation for the latest released version of Pundit.

bash
bundle add pundit

Include Pundit::Authorization in your application controller:

ruby
class ApplicationController < ActionController::Base
  include Pundit::Authorization
end

Optionally, you can run the generator, which will set up an application policy with some useful defaults for you:

bash
rails g pundit:install

After generating your application policy, restart the Rails server so that Rails can pick up any classes in the new app/policies/ directory.

Policies

Pundit is focused around the notion of policy classes. We suggest that you put these classes in app/policies. This is an example that allows updating a post if the user is an admin, or if the post is unpublished:

ruby
class PostPolicy
  attr_reader :user, :post

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

  def update?
    user.admin? || !post.published?
  end
end

As you can see, this is a plain Ruby class. Pundit makes the following assumptions about this class:

  • The class has the same name as some kind of model class, only suffixed with the word "Policy".
  • The first argument is a user. In your controller, Pundit will call the current_user method to retrieve what to send into this argument
  • The second argument is some kind of model object, whose authorization you want to check. This does not need to be an ActiveRecord or even an ActiveModel object, it can be anything really.
  • The class implements some kind of query method, in this case update?. Usually, this will map to the name of a particular controller action.

That's it really.

Usually you'll want to inherit from the application policy created by the generator, or set up your own base class to inherit from:

ruby
class PostPolicy < ApplicationPolicy
  def update?
    user.admin? or not record.published?
  end
end

In the generated ApplicationPolicy, the model object is called record.

Supposing that you have an instance of class Post, Pundit now lets you do this in your controller:

ruby
def update
  @post = Post.find(params[:id])
  authorize @post
  if @post.update(post_params)
    redirect_to @post
  else
    render :edit
  end
end

The authorize method automatically infers that Post will have a matching PostPolicy class, and instantiates this class, handing in the current user and the given record. It then infers from the action name, that it should call update? on this instance of the policy. In this case, you can imagine that authorize would have done something like this:

ruby
unless PostPolicy.new(current_user, @post).update?
  raise Pundit::NotAuthorizedError, "not allowed to PostPolicy#update? this Post"
end

You can pass a second argument to authorize if the name of the permission you want to check doesn't match the action name. For example:

ruby
def publish
  @post = Post.find(params[:id])
  authorize @post, :update?
  @post.publish!
  redirect_to @post
end

You can pass an argument to override the policy class if necessary. For example:

ruby
def create
  @publication = find_publication # assume this method returns any model that behaves like a publication
  # @publication.class => Post
  authorize @publication, policy_class: PublicationPolicy
  @publication.publish!
  redirect_to @publication
end

If you don't have an instance for the first argument to authorize, then you can pass the class. For example:

Policy:

ruby
class PostPolicy < ApplicationPolicy
  def admin_list?
    user.admin?
  end
end

Controller:

ruby
def admin_list
  authorize Post # we don't have a particular post to authorize
  # Rest of controller action
end

authorize returns the instance passed to it, so you can chain it like this:

Controller:

ruby
def show
  @user = authorize User.find(params[:id])
end

You can easily get a hold of an instance of the policy through the policy method in both the view and controller. This is especially useful for conditionally showing links or buttons in the view:

erb
<% if policy(@post).update? %>
  <%= link_to "Edit post", edit_post_path(@post) %>
<% end %>

Headless policies

Given there is a policy without a corresponding model / ruby class, you can retrieve it by passing a symbol.

ruby
# app/policies/dashboard_policy.rb
class DashboardPolicy
  attr_reader :user

  # `_record` in this example will be :dashboard
  def initialize(user, _record)
    @user = user
  end

  def show?
    user.admin?
  end
end

Note that the headless policy still needs to accept two arguments. The second argument will be the symbol :dashboard in this case, which is what is passed as the record to authorize below.

ruby
# In controllers
def show
  authorize :dashboard, :show?
  ...
end
erb
# In views
<% if policy(:dashboard).show? %>
  <%= link_to 'Dashboard', dashboard_path %>
<% end %>

Scopes

Often, you will want to have some kind of view listing records which a particular user has access to. When using Pundit, you are expected to define a class called a policy scope. It can look something like this:

ruby
class PostPolicy < ApplicationPolicy
  class Scope
    def initialize(user, scope)
      @user  = user
      @scope = scope
    end

    def resolve
      if user.admin?
        scope.all
      else
        scope.where(published: true)
      end
    end

    private

    attr_reader :user, :scope
  end

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

Pundit makes the following assumptions about this class:

  • The class has the name Scope and is nested under the policy class.
  • The first argument is a user. In your controller, Pundit will call the current_user method to retrieve what to send into this argument.
  • The second argument is a scope of some kind on which to perform some kind of query. It will usually be an ActiveRecord class or a ActiveRecord::Relation, but it could be something else entirely.
  • Instances of this class respond to the method resolve, which should return some kind of result which can be iterated over. For ActiveRecord classes, this would usually be an ActiveRecord::Relation.

You'll probably want to inherit from the application policy scope generated by the generator, or create your own base class to inherit from:

ruby
class PostPolicy < ApplicationPolicy
  class Scope < ApplicationPolicy::Scope
    def resolve
      if user.admin?
        scope.all
      else
        scope.where(published: true)
      end
    end
  end

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

You can now use this class from your controller via the policy_scope method:

ruby
def index
  @posts = policy_scope(Post)
end

def show
  @post = policy_scope(Post).find(params[:id])
end

Like with the authorize method, you can also override the policy scope class:

ruby
def index
  # publication_class => Post
  @publications = policy_scope(publication_class, policy_scope_class: PublicationPolicy::Scope)
end

In this case it is a shortcut for doing:

ruby
def index
  @publications = PublicationPolicy::Scope.new(current_user, Post).resolve
end

You can, and are encouraged to, use this method in views:

erb
<% policy_scope(@user.posts).each do |post| %>
  <p><%= link_to post.title, post_path(post) %></p>
<% end %>

Ensuring policies and scopes are used

When you are developing an application with Pundit it can be easy to forget to authorize some action. People are forgetful after all. Since Pundit encourages you to add the authorize call manually to each controller action, it's really easy to miss one.

Thankfully, Pundit has a handy feature which reminds you in case you forget. Pundit tracks whether you have called authorize anywhere in your controller action. Pundit also adds a method to your controllers called verify_authorized. This method will raise an exception if authorize has not yet been called. You should run this method in an after_action hook to ensure that you haven't forgotten to authorize the action. For example:

ruby
class ApplicationController < ActionController::Base
  include Pundit::Authorization
  after_action :verify_authorized
end

Likewise, Pundit also adds verify_policy_scoped to your controller. This will raise an exception similar to verify_authorized. However, it tracks if policy_scope is used instead of authorize. This is mostly useful for controller actions like index which find collections with a scope and don't authorize individual instances.

ruby
class ApplicationController < ActionController::Base
  include Pundit::Authorization
  after_action :verify_pundit_authorization

  def verify_pundit_authorization
    if action_name == "index"
      verify_policy_scoped
    else
      verify_authorized
    end
  end
end

This verification mechanism only exists to aid you while developing your application, so you don't forget to call authorize. It is not some kind of failsafe mechanism or authorization mechanism. You should be able to remove these filters without affecting how your app works in any way.

Some people have found this feature confusing, while many others find it extremely helpful. If you fall into the category of people who find it confusing then you do not need to use it. Pundit will work fine without using verify_authorized and verify_policy_scoped.

Conditional verification

If you're using verify_authorized in your controllers but need to conditionally bypass verification, you can use skip_authorization. For bypassing verify_policy_scoped, use skip_policy_scope. These are useful in circumstances where you don't want to disable verification for the entire action, but have some cases where you intend to not authorize.

ruby
def show
  record = Record.find_by(attribute: "value")
  if record.present?
    authorize record
  else
    skip_authorization
  end
end

Manually specifying policy classes

Sometimes you might want to explicitly declare which policy to use for a given class, instead of letting Pundit infer it. This can be done like so:

ruby
class Post
  def self.policy_class
    PostablePolicy
  end
end

Alternatively, you can declare an instance method:

ruby
class Post
  def policy_class
    PostablePolicy
  end
end

Plain old Ruby

Pundit is a very small library on purpose, and it doesn't do anything you can't do yourself. There's no secret sauce here.

Issues· 14 open

View all issuesOpen on GitHub
  • #885

    `permit` passes both `to` and `not_to` when a `permissions` group names no permissions

    Updated Sep 27, 2026
  • #735

    [Request] Generate policy file when using scaffolding

    good first issueUpdated Aug 15, 2026
  • #740

    Adjust policy-lookup behaviour (e.g. always use same policy class)

    waiting for responseUpdated Feb 6, 2025
  • #654

    Here we go again: Custom error messages?

    feature requestUpdated Oct 1, 2024
  • #728

    Per-query level verify_pundit_policy_scoped

    feature requestwaiting for responseUpdated Oct 1, 2024
  • #746

    Split this into two methods?

    simmeringUpdated Aug 8, 2024
  • #742

    Add `policy_class` parameter to `permitted_attributes` function

    simmeringUpdated Aug 8, 2024
  • #723

    Overriding both authorize and policy is required for namespacing

    good first issueUpdated May 15, 2024
  • #368

    Getting a scope for a specific action

    feature requestUpdated Oct 28, 2023

> Tags

Rubyruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 30, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言