Pundit is Minimal authorization through OO design and pure Ruby classes.
[code language=”ruby”] gem pundit[/code]
Include Pundit in your application controller:
[code language=”ruby”]
class ApplicationController < ActionController::Base
include Pundit
protect_from_forgery
end
[/code]
]
Optionally, you can run the generator, which will set up an application policy with some useful defaults for you:
[code language=”ruby”]rails g pundit:install[/code]
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. Put policies classes in app/policies.
This is a simple example that allows updating a post if the user is an admin, or if the post is unpublished:
[code language=”ruby”]
class ArticlePolicy
attr_reader :user, :article
def initialize(user,article)
@user = user
@article = article
end
def index?
user.admin?
end
def update?
user.admin? or not article.published?
end
end
[/code]
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.