class Pundit::PolicyFinder
finder.scope #=> UserPolicy::Scope
finder.policy #=> UserPolicy
finder = PolicyFinder.new(user)
user = User.find(params)
@example
@api public
Finds policy and scope classes for given object.
def find(subject)
def find(subject) if subject.is_a?(Array) modules = subject.dup last = modules.pop context = modules.map { |x| find_class_name(x) }.join("::") [context, find(last)].join("::") elsif subject.respond_to?(:policy_class) subject.policy_class elsif subject.class.respond_to?(:policy_class) subject.class.policy_class else klass = find_class_name(subject) "#{klass}#{SUFFIX}" end end
def find_class_name(subject)
def find_class_name(subject) if subject.respond_to?(:model_name) subject.model_name elsif subject.class.respond_to?(:model_name) subject.class.model_name elsif subject.is_a?(Class) subject elsif subject.is_a?(Symbol) subject.to_s.camelize else subject.class end end
def initialize(object)
-
object
(any
) -- the object to find policy and scope classes for
def initialize(object) @object = object end
def param_key
-
(String)
- the name of the key this object would have in a params hash
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
def policy
- See: https://github.com/varvet/pundit#policies -
Returns:
-
(nil, Class)
- policy class with query methods
def policy klass = find(object) klass.is_a?(String) ? klass.safe_constantize : klass end
def policy!
-
(NotDefinedError)
- if policy could not be determined
Returns:
-
(Class)
- policy class with query methods
def policy! policy or raise NotDefinedError, "unable to find policy `#{find(object)}` for `#{object.inspect}`" end
def scope
- See: https://github.com/varvet/pundit#scopes -
Returns:
-
(nil, Scope{#resolve})
- scope class which can resolve to a scope
def scope "#{policy}::Scope".safe_constantize end
def scope!
-
(NotDefinedError)
- if scope could not be determined
Returns:
-
(Scope{#resolve})
- scope class which can resolve to a scope
def scope! scope or raise NotDefinedError, "unable to find scope `#{find(object)}::Scope` for `#{object.inspect}`" end