[ rails ] Pundit — Validation, rescue_from

Overview

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 )

/app/policies/post_policy.rb

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

 

Controller

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

Controller

@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.

ref : https://github.com/elabs/pundit,

http://www.rubydoc.info/gems/pundit

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s