/
punditize.rb
60 lines (50 loc) · 1.59 KB
/
punditize.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
module Administrate
module Punditize
if Object.const_defined?(:Pundit)
extend ActiveSupport::Concern
if Pundit.const_defined?(:Authorization)
include Pundit::Authorization
else
include Pundit
end
private
def policy_namespace
[]
end
def scoped_resource
namespaced_scope = policy_namespace + [super]
policy_scope!(pundit_user, namespaced_scope)
end
def authorize_resource(resource)
namespaced_resource = policy_namespace + [resource]
authorize namespaced_resource
end
def authorized_action?(resource, action)
namespaced_resource = policy_namespace + [resource]
policy = Pundit.policy!(pundit_user, namespaced_resource)
policy.send(:"#{action}?")
end
def policy_scope!(user, scope)
policy_scope_class = Pundit::PolicyFinder.new(scope).scope!
begin
policy_scope = policy_scope_class.new(user, pundit_model(scope))
rescue ArgumentError
raise(Pundit::InvalidConstructorError,
"Invalid #<#{policy_scope_class}> constructor is called")
end
if policy_scope.respond_to? :resolve_admin
Administrate.deprecator.warn(
"Pundit policy scope `resolve_admin` method is deprecated. " \
"Please use a namespaced pundit policy instead."
)
policy_scope.resolve_admin
else
policy_scope.resolve
end
end
def pundit_model(record)
record.is_a?(Array) ? record.last : record
end
end
end
end