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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ PolicyFinder

Returns a new instance of PolicyFinder


15
16
17
# File 'lib/pundit/policy_finder.rb', line 15

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject (readonly)


11
12
13
# File 'lib/pundit/policy_finder.rb', line 11

def object
  @object
end

Instance Method Details

#param_keyString

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


64
65
66
67
68
69
70
71
72
# File 'lib/pundit/policy_finder.rb', line 64

def param_key
  if object.respond_to?(:model_name)
    object.model_name.param_key.to_s
  elsif object.is_a?(Class)
    object.to_s.demodulize.underscore
  else
    object.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:


38
39
40
41
42
43
44
# File 'lib/pundit/policy_finder.rb', line 38

def policy
  klass = find
  klass = klass.constantize if klass.is_a?(String)
  klass
rescue NameError
  nil
end

#policy!Class

Returns policy class with query methods

Raises:


57
58
59
60
# File 'lib/pundit/policy_finder.rb', line 57

def policy!
  raise NotDefinedError, "unable to find policy of nil" if object.nil?
  policy or raise NotDefinedError, "unable to find policy `#{find}` 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:


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

def scope
  policy::Scope if policy
rescue NameError
  nil
end

#scope!Scope{#resolve}

Returns scope class which can resolve to a scope

Raises:


49
50
51
52
# File 'lib/pundit/policy_finder.rb', line 49

def scope!
  raise NotDefinedError, "unable to find policy scope of nil" if object.nil?
  scope or raise NotDefinedError, "unable to find scope `#{find}::Scope` for `#{object.inspect}`"
end