Implement Pundit for an App Permission Structure
In this section, we are going to streamline the permission structure for the entire application using a gem called `Pundit`. This app component will manage the authorization rules so that users are only able to perform the tasks that we want them to do.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this section, we are going to streamline the permission structure for the entire application using a gem called Pundit. This app component will manage the authorization rules so that users are only able to perform the tasks that we want them to do.

Let's start with updating our Gemfile to include the gem:

gem 'pundit' , '~>1.1'

As always, make sure to check RubyGems.org to ensure that you're using the most up to date version of the gem.

Next, we'll ask rails to install all of the pundit dependencies by typing bundle in the console.

Then, we'll run the pundit generator with the command:

rails g pundit:install

This generator created a file called application_policy.rb. This is what the file looks like:

# app/policies/application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

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

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  class Scope
    attr_reader :user, :scope

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

    def resolve
      scope
    end
  end
end

Though you can edit these methods, it's rarely done in practice. Instead we are going to create custom policies that inherit from ApplicationPolicy. This will allow us to build our permission structure and call our policy methods from controller files. It's a great and elegant way to manage permissions.

Resources