Class: ActiveAdmin::PunditAdapter

Inherits:
AuthorizationAdapter show all
Defined in:
lib/active_admin/pundit_adapter.rb

Instance Attribute Summary

Attributes inherited from AuthorizationAdapter

#resource, #user

Instance Method Summary collapse

Methods inherited from AuthorizationAdapter

#initialize

Constructor Details

This class inherits a constructor from ActiveAdmin::AuthorizationAdapter

Instance Method Details

#authorized?(action, subject = nil) ⇒ Boolean

Returns:

  • (Boolean)

12
13
14
15
16
17
# File 'lib/active_admin/pundit_adapter.rb', line 12

def authorized?(action, subject = nil)
  policy = retrieve_policy(subject)
  action = format_action(action, subject)

  policy.respond_to?(action) && policy.public_send(action)
end

#format_action(action, subject) ⇒ Object


45
46
47
48
49
50
51
52
53
54
# File 'lib/active_admin/pundit_adapter.rb', line 45

def format_action(action, subject)
  # https://github.com/elabs/pundit/blob/master/lib/generators/pundit/install/templates/application_policy.rb
  case action
  when Auth::CREATE  then :create?
  when Auth::UPDATE  then :update?
  when Auth::READ    then subject.is_a?(Class) ? :index? : :show?
  when Auth::DESTROY then subject.is_a?(Class) ? :destroy_all? : :destroy?
  else "#{action}?"
  end
end

#retrieve_policy(subject) ⇒ Object


31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/active_admin/pundit_adapter.rb', line 31

def retrieve_policy(subject)
  case subject
  when nil   then Pundit.policy!(user, resource)
  when Class then Pundit.policy!(user, subject.new)
  else Pundit.policy!(user, subject)
  end
rescue Pundit::NotDefinedError => e
  if default_policy_class
    default_policy(user, subject)
  else
    raise e
  end
end

#scope_collection(collection, action = Auth::READ) ⇒ Object


19
20
21
22
23
24
25
26
27
28
29
# File 'lib/active_admin/pundit_adapter.rb', line 19

def scope_collection(collection, action = Auth::READ)
  # scoping is appliable only to read/index action
  # which means there is no way how to scope other actions
  Pundit.policy_scope!(user, collection)
rescue Pundit::NotDefinedError => e
  if default_policy_class && default_policy_class.const_defined?(:Scope)
    default_policy_class::Scope.new(user, collection).resolve
  else
    raise e
  end
end