PunditExtra
This library borrows functionality from CanCan(Can) and adds it to Pundit.
can?andcannot?view helpersload_resource,authorize_resource,load_and_authorize_resourceandskip_authorizationcontroller filters
The design intentions were:
- To ease the transition from CanCanCan to Pundit.
- To reduce boilerplate code in controller methods.
- To keep things simple and intentionally avoid dealing with edge cases or endless magical options you need to memorize.
Install
Add to your Gemfile:
gem 'pundit_extra'
Add to your ApplicationController:
class ApplicationController < ActionController::Base
include Pundit
include PunditExtra
end
View Helpers: can? and cannot?
You can use the convenience methods can? and cannot? in any controller
and view.
if can? :assign, @taskis the same as Pundit'spolicy(@task).assign?if can? :index, Taskis the same as Pundit'spolicy(Task).index?if cannot? :assign, @taskis the opposite ofcan?
Autoload and Authorize Resource
You can add these to your controllers to automatically load the resource and/or authorize it.
class TasksController < ApplicationController
before_action :authenticate_user!
load_resource except: [:index, :create]
except: [:create]
end
The load_resource filter will create the appropriate instance variable
based onm the current action.
The authorize_resource filter will call Pundit's authorize @model in each
action.
You can use except: :action, or only: :action to limit the filter to a
given action or an array of actions.
Example:
class TasksController < ApplicationController
before_action :authenticate_user!
load_resource except: [:edit, :complete]
except: :index
def index
# this happens automatically
# @tasks = policy_scope(Task)
end
def show
# this happens automatically
# @task = Task.find params[:id]
# authorize @task
end
def new
# this happens automatically
# @task = Task.new
# authorize @task
end
def create
# this happens automatically
# @task = Task.new task_params
# authorize @task
end
end
In addition, you can use:
load_and_authorize_resourcewhich is a combination shortcut forload_resourceandauthorize_resourceskip_authorizationwhich sendsskip_authorizationandskip_policy_scopeto Pundit for all (or the specified) actions.
Credits
Thanks for building awesome stuff.