Class: MayMay::Ability

Inherits:
Object
  • Object
show all
Defined in:
lib/maymay/ability.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user) ⇒ Ability

Returns a new instance of Ability.



3
4
5
6
# File 'lib/maymay/ability.rb', line 3

def initialize(user)
  @abilities = {}
  @user = user
end

Class Method Details

.reset!Object



8
9
10
# File 'lib/maymay/ability.rb', line 8

def self.reset!
  @abilities = {}
end

Instance Method Details

#authorize!(*args) ⇒ Object



38
39
40
41
42
# File 'lib/maymay/ability.rb', line 38

def authorize!(*args)
  if maynot?(*args)
    raise Unauthorized
  end
end

#may(action, subject, &block) ⇒ Object



26
27
28
29
30
# File 'lib/maymay/ability.rb', line 26

def may(action, subject, &block)
  @abilities[subject] ||= []
  @abilities[subject] << [true, action, block]
  nil
end

#may?(action, subject, object = nil) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
20
# File 'lib/maymay/ability.rb', line 12

def may?(action, subject, object = nil)
  unless @abilities.has_key?(subject)
    raise UndefinedAbility.new(action, subject)
  end
  actions = @abilities[subject].find_all { |a| a[1] == action }
  actions.all? do |a|
    a[0] == !!(!a[2] || a[2].call(@user, object))
  end
end

#maynot(action, subject, &block) ⇒ Object



32
33
34
35
36
# File 'lib/maymay/ability.rb', line 32

def maynot(action, subject, &block)
  @abilities[subject] ||= []
  @abilities[subject] << [false, action, block]
  nil
end

#maynot?(action, subject, object = nil) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/maymay/ability.rb', line 22

def maynot?(action, subject, object = nil)
  !may?(action, subject, object)
end