Rails Authorization With Pundit

I’ve completed a new tutorial on Rails authorization with Pundit.

RailsApps subscribers are getting tutorials every month:

You can join RailsApps to get the tutorials and support the project. Coming next is a tutorial on OmniAuth.

Role-Based Authorization

The new tutorial covers role-based authorization, showing how to use the Active Record enum feature in Rails 4.1 to add a role attribute to a User model. You can set up roles for administrators, users with free or premium plans, or any other system of privileges. The tutorial shows how you can set up simple role-based authorization without any extra gems. For more complex applications, the tutorial introduces the Pundit authorization gem.

Pundit or CanCan?

The CanCan authorization gem has been popular since Ryan Bates released it four years ago (it’s been recently replaced by its successor, CanCanCan). CanCan provides a domain-specific language that isolates all authorization logic in a single Ability class. As an application grows in complexity, the CanCan Ability class can grow unwieldy. Every authorization request requires evaluation of the full CanCan Ability class, adding performance overhead. Like CanCan, Pundit offers the advantage of segregating access rules into a central location. In Pundit, it’s a folder named app/policies/ containing plain Ruby objects that implement access rules. Pundit policy objects are lightweight, adding authorization logic without as much overhead as CanCan. Pundit is well-suited to the service-oriented architecture that is growing in popularity among Rails developers, emphasizing object-oriented design with discrete Ruby objects providing specialized services.

In-Depth Pundit Tutorial

For a small gem, Pundit has a surprising number of features. The RailsApps tutorial goes into depth, covering:

  • set up with a starter app
  • adding roles to the User model
  • access rules in a policy object
  • authorization in controllers
  • authorization in views
  • scoped database queries
  • strong parameters
  • adding RSpec tests for authorization

It’s the only in-depth guide to Pundit. I appreciate the support from RailsApps subscribers that made it possible to release this tutorial.

1 noteShowHide

  1. rails-apps posted this