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



17
18
19
# File 'lib/pundit/policy_finder.rb', line 17

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject (readonly)



13
14
15
# File 'lib/pundit/policy_finder.rb', line 13

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



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

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

Returns:

  • (nil, Class)

    policy class with query methods

See Also:



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

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:



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

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:



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

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:



46
47
48
# File 'lib/pundit/policy_finder.rb', line 46

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