Class: Pundit::PolicyFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/pundit/policy_finder.rb

Overview

Finds policy and scope classes for given object.

Examples:

user = User.find(params[:id])
finder = PolicyFinder.new(user)
finder.policy #=> UserPolicy
finder.scope #=> UserPolicy::Scope

Since:

  • v0.1.0

Constant Summary collapse

SUFFIX =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

A constant applied to the end of the class name to find the policy class.

Since:

  • v2.5.0

"Policy"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ PolicyFinder

Returns a new instance of PolicyFinder.

Since:

  • v0.1.0



29
30
31
# File 'lib/pundit/policy_finder.rb', line 29

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject (readonly)

See Also:

Since:

  • v0.1.0



25
26
27
# File 'lib/pundit/policy_finder.rb', line 25

def object
  @object
end

Instance Method Details

#param_keyString

Returns the name of the key this object would have in a params hash.

Since:

  • v1.1.0



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/pundit/policy_finder.rb', line 76

def param_key # rubocop:disable Metrics/AbcSize
  model = object.is_a?(Array) ? object.last : object

  if model.respond_to?(:model_name)
    model.model_name.param_key.to_s
  elsif model.is_a?(Class)
    model.to_s.demodulize.underscore
  else
    model.class.to_s.demodulize.underscore
  end
end

#policynil, Class

Returns policy class with query methods.

Examples:

policy = finder.policy #=> UserPolicy
policy.show? #=> true
policy.update? #=> false

See Also:

Since:

  • v0.1.0



52
53
54
55
# File 'lib/pundit/policy_finder.rb', line 52

def policy
  klass = find(object)
  klass.is_a?(String) ? klass.safe_constantize : klass
end

#policy!Class

Returns policy class with query methods.

Raises:

Since:

  • v0.1.0



69
70
71
# File 'lib/pundit/policy_finder.rb', line 69

def policy!
  policy or raise NotDefinedError, "unable to find policy `#{find(object)}` for `#{object.inspect}`"
end

#scopenil, Scope{#resolve}

Returns scope class which can resolve to a scope.

Examples:

scope = finder.scope #=> UserPolicy::Scope
scope.resolve #=> <#ActiveRecord::Relation ...>

See Also:

Since:

  • v0.1.0



40
41
42
# File 'lib/pundit/policy_finder.rb', line 40

def scope
  "#{policy}::Scope".safe_constantize
end

#scope!Scope{#resolve}

Returns scope class which can resolve to a scope.

Raises:

Since:

  • v0.1.0



61
62
63
# File 'lib/pundit/policy_finder.rb', line 61

def scope!
  scope or raise NotDefinedError, "unable to find scope `#{find(object)}::Scope` for `#{object.inspect}`"
end