Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/authorizer/active_record_patch.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define_rule(*names, &block) ⇒ Object



15
16
17
18
# File 'lib/authorizer/active_record_patch.rb', line 15

def self.define_rule(*names, &block)
  perms = self.get_perms
  names.each {|name| perms[name.to_sym] = block}
end

.get_permsObject



3
4
5
6
7
8
9
# File 'lib/authorizer/active_record_patch.rb', line 3

def self.get_perms
  unless (self.class_variables.include?(:'@@perms'))
    @@perms = {}
  end
  init_fallback_rule
  return @@perms
end

.init_fallback_ruleObject



11
12
13
# File 'lib/authorizer/active_record_patch.rb', line 11

def self.init_fallback_rule
  @@fallback_rule = nil unless (self.class_variable_defined?(:@@fallback_rule))
end

.set_fallback_rule(&rule) ⇒ Object



20
21
22
# File 'lib/authorizer/active_record_patch.rb', line 20

def self.set_fallback_rule(&rule)
  @@fallback_rule = rule
end

Instance Method Details

#is_authorized(action, authorizee) ⇒ Object

Raises:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/authorizer/active_record_patch.rb', line 24

def is_authorized(action, authorizee)
  symbol = action.to_sym
  perms = self.class.get_perms

  authorized = false
  authorized = perms[symbol].(self, authorizee) if perms[symbol]
  authorized = @@fallback_rule.(self, authorizee) if @@fallback_rule && !perms[symbol]

  raise ForbiddenError.new(
    "Actor #{authorizee} is not authorized to perform action #{action} on resource #{self}."
  ) unless authorized

  self
end