Class: Pragma::Policy::Pundit

Inherits:
Base
  • Object
show all
Defined in:
lib/pragma/policy/pundit.rb

Overview

Provides a simple way for Pragma policies to delegate to Pundit policies/scopes.

Examples:

class API::V1::Article::Policy < Pragma::Policy::Pundit
  # The default would be ArticlePolicy.
  self.pundit_klass = CustomArticlePolicy
end

Constant Summary

Constants inherited from Base

Base::Scope

Class Attribute Summary collapse

Attributes inherited from Base

#record, #user

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#authorize

Constructor Details

#initialize(user, record) ⇒ Pundit

Returns a new instance of Pundit.



42
43
44
45
# File 'lib/pragma/policy/pundit.rb', line 42

def initialize(user, record)
  super
  @pundit_policy = self.class.pundit_klass.new(user, record)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



51
52
53
54
# File 'lib/pragma/policy/pundit.rb', line 51

def method_missing(method_name, *args, &block)
  return super unless @pundit_policy.respond_to?(method_name)
  @pundit_policy.send(method_name, *args, &block)
end

Class Attribute Details

.pundit_klassObject



16
17
18
# File 'lib/pragma/policy/pundit.rb', line 16

def pundit_klass
  @pundit_klass ||= Object.const_get("#{self.class.name.split('::')[-2]}Policy")
end

Class Method Details

.inherited(base) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/pragma/policy/pundit.rb', line 20

def inherited(base)
  base.class_eval <<~RUBY, __FILE__, __LINE__ + 1
    class Scope < Pragma::Policy::Scope
      def initialize(user, scope)
        super
        @pundit_scope = pundit_scope_klass.new(user, scope)
      end

      def resolve
        @pundit_scope.resolve
      end

      private

      def pundit_scope_klass
        policy_klass.pundit_klass.const_get('Scope')
      end
    end
  RUBY
end

Instance Method Details

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/pragma/policy/pundit.rb', line 47

def respond_to_missing?(method_name, include_private = false)
  super || @pundit_policy.respond_to?("#{method_name[0..-2]}?", include_private)
end