Sha256: 0ee76584e0ff1a737a1adea97324e6bfad4125721b17d34b6e68addc5e5c8f61

Contents?: true

Size: 1.05 KB

Versions: 4

Compression:

Stored size: 1.05 KB

Contents

module Pundit
  class PolicyFinder
    attr_reader :object

    def initialize(object)
      @object = object
    end

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

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

    def scope!
      scope or raise NotDefinedError, "unable to find scope #{find}::Scope for #{object}"
    end

    def policy!
      policy or raise NotDefinedError, "unable to find policy #{find} for #{object}"
    end

  private

    def find
      if object.respond_to?(:policy_class)
        object.policy_class
      elsif object.class.respond_to?(:policy_class)
        object.class.policy_class
      else
        klass = if object.respond_to?(:model_name)
          object.model_name
        elsif object.class.respond_to?(:model_name)
          object.class.model_name
        elsif object.is_a?(Class)
          object
        else
          object.class
        end
        "#{klass}Policy"
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
pundit-0.2.3 lib/pundit/policy_finder.rb
pundit-0.2.2 lib/pundit/policy_finder.rb
pundit-0.2.1 lib/pundit/policy_finder.rb
pundit-0.2.0 lib/pundit/policy_finder.rb