Class: Weeter::Limitator

Inherits:
Object
  • Object
show all
Defined in:
lib/weeter/limitator.rb

Defined Under Namespace

Modules: UNLIMITED Classes: Result, TimeWindow

Constant Summary collapse

DO_NOT_LIMIT =
:do_not_limit
INITIATE_LIMITING =
:initiate_limiting
CONTINUE_LIMITING =
:continue_limiting

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Limitator

Returns a new instance of Limitator.



34
35
36
37
38
39
40
41
42
43
# File 'lib/weeter/limitator.rb', line 34

def initialize(options = {})
  self.window = TimeWindow.new({
    start: self.now,
    duration: options.fetch(:duration)
  })

  self.max = options.fetch(:max)

  flush
end

Instance Attribute Details

#lookupObject

Returns the value of attribute lookup.



32
33
34
# File 'lib/weeter/limitator.rb', line 32

def lookup
  @lookup
end

#maxObject

Returns the value of attribute max.



32
33
34
# File 'lib/weeter/limitator.rb', line 32

def max
  @max
end

#windowObject

Returns the value of attribute window.



32
33
34
# File 'lib/weeter/limitator.rb', line 32

def window
  @window
end

Instance Method Details

#process(*keys) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/weeter/limitator.rb', line 45

def process(*keys)
  ensure_correct_window

  keys.each do |key|
    increment(key)
  end

  result = Result.new
  limited_keys = keys.select { |key| exceeds_max?(key) }
  if limited_keys.any?
    result[:limited_keys] = limited_keys
    if limited_keys.any? { |key| exceeds_max_by_one?(key) }
      result[:status] = INITIATE_LIMITING
    else
      result[:status] = CONTINUE_LIMITING
    end
  else
    result[:status] = DO_NOT_LIMIT
  end
  result
end