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.

Parameters:

  • object (any)

    the object to find policy and scope classes for



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.

Returns:

  • (String)

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



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/pundit/policy_finder.rb', line 57

def param_key
  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

Returns:

  • (nil, Class)

    policy class with query methods

See Also:



36
37
38
39
# File 'lib/pundit/policy_finder.rb', line 36

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

#policy!Class

Returns policy class with query methods.

Returns:

  • (Class)

    policy class with query methods

Raises:



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

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

Returns:

  • (nil, Scope{#resolve})

    scope class which can resolve to a scope

See Also:



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

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

#scope!Scope{#resolve}

Returns scope class which can resolve to a scope.

Returns:

  • (Scope{#resolve})

    scope class which can resolve to a scope

Raises:



44
45
46
# File 'lib/pundit/policy_finder.rb', line 44

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