Pundit is Minimal authorization through OO design and pure Ruby classes.
[code language=”ruby”] gem pundit[/code]
Include Pundit in your application controller:
class ApplicationController < ActionController::Base
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
Pundit is focused around the notion of policy classes. Put policies classes in
This is a simple example that allows updating a post if the user is an admin, or if the post is unpublished:
attr_reader :user, :article
@user = user
@article = article
user.admin? or not article.published?
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_usermethod 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.