Class: Permits::Policy::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Attributes, ActiveModel::Model, ActiveModel::Validations
Defined in:
lib/permits/policy/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.authorize!(owner, resource, action) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/permits/policy/base.rb', line 14

def self.authorize!(owner, resource, action)
  policy = new(owner: owner, resource: resource)
  if policy.authorized?(action)
    true
  else
    raise ::Permits::Policy::UnauthorizedError
  end
end

.authorized?(owner, resource, action) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
26
# File 'lib/permits/policy/base.rb', line 23

def self.authorized?(owner, resource, action)
  policy = new(owner: owner, resource: resource)
  policy.authorized?(action)
end

Instance Method Details

#authorized?(action) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
34
35
36
# File 'lib/permits/policy/base.rb', line 28

def authorized?(action)
  return false unless valid?

  if respond_to?("#{action}?")
    send("#{action}?")
  else
    has_action_permissions?(action)
  end
end

#has_action_permissions?(action, for_resource: resource, for_resource_type: nil, for_resource_id: nil) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
# File 'lib/permits/policy/base.rb', line 38

def has_action_permissions?(action, for_resource: resource, for_resource_type: nil, for_resource_id: nil)
  return false unless owner_permissions.respond_to?("permits_#{action}")

  if for_resource_type && for_resource_id
    owner_permissions.send("permits_#{action}").where(resource_type: for_resource_type, resource_id: for_resource_id).exists?
  else
    owner_permissions.send("permits_#{action}").where(resource: for_resource).exists?
  end
end