Module: ActionPolicy::Policy::PreCheck

Included in:
Base
Defined in:
lib/action_policy/policy/pre_check.rb

Overview

Adds callback-style checks to policies to extract common checks from rules.

class ApplicationPolicy < ActionPolicy::Base
  authorize :user
  pre_check :allow_admins

  private
    # Allow every action for admins
    def allow_admins
      allow! if user.admin?
    end
end

You can specify conditional pre-checks (through ‘except` / `only`) options and skip already defined pre-checks if necessary.

class UserPolicy < ApplicationPolicy
  skip_pre_check :allow_admins, only: :destroy?

  def destroy?
    user.admin? && !record.admin?
  end
end

Defined Under Namespace

Modules: ClassMethods Classes: Check

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



108
109
110
# File 'lib/action_policy/policy/pre_check.rb', line 108

def included(base)
  base.extend ClassMethods
end

Instance Method Details

#__apply__(rule) ⇒ Object



122
123
124
# File 'lib/action_policy/policy/pre_check.rb', line 122

def __apply__(rule)
  run_pre_checks(rule) { super }
end

#run_pre_checks(rule) ⇒ Object



113
114
115
116
117
118
119
120
# File 'lib/action_policy/policy/pre_check.rb', line 113

def run_pre_checks(rule)
  self.class.pre_checks.each do |check|
    next unless check.applicable?(rule)
    check.call(self)
  end

  yield if block_given?
end