Minimal authorization through OO design and pure Ruby classes. This implement the Gang of 4’s
Strategy Pattern. ( https://en.wikipedia.org/wiki/Strategy_pattern )
class PostPolicy < ApplicationPolicy attr_reader :user, :post def initialize(user, record) @user = user @record = record end def create? user.present? end def update? user.admin? or not record.published? end end
include Pundit protect_from_forgery with: :null_session rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized private def user_not_authorized flash[:alert] = "You are not authorized to perform this action." redirect_to(request.referrer || root_path) end
@post = Post.find(params[:id]) authorize @post # init if @post.update(post_params) # call update? in policy redirect_to @post else render :edit end
- 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.
Tests for your policies in RSpec
Require pundit/rspec in your spec_helper.rb
Then put your policy specs in spec/policies.