A few coworkers and I recently jumped on the Pundit train a few
weeks ago, and by far we can all agree that it’s been the highlight
of our recent development in Rails recently.
Pundit is an authorization gem that works with multiple finely tuned classes,
as opposed to cancancan which restricts you to a single class. For more
complex business logic, Pundit allows you to create hierarchies of
inherited permissions, and split your rule sets out by resource.
Pundit classes look like the following.
Each class is called a policy and correlates to a resource
with methods. In this case, this policy matches a PolicyController
in a Rails app. It’s common practice to extend off a base policy
where default permissions and useful private methods can be defined.
Now, this format does mean that updating controllers takes the extra steps
of keeping your policies and policy tests up to date, but the logic
involved is usually not that complex and worth the low level control
that is provided.
Testing is also really simple as well with the built in
test helpers. You only need to make sure that you have an instance
of a user and a record. Then you just assert that the user has permission to
act on the record in each permission block like so.
Though the examples above are from my personal project called
Gitfolio, this pattern has been tremendously successful in my current
project at work, allowing us to adapt very quickly to changing requirements
with fine detail.