Class: RateLimitMockServer::Counter

Inherits:
Object
  • Object
show all
Defined in:
lib/rate_limit_mock_server/counter.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rps_limit) ⇒ Counter

Returns a new instance of Counter.



20
21
22
23
# File 'lib/rate_limit_mock_server/counter.rb', line 20

def initialize(rps_limit)
  @rps_limit = rps_limit
  @window = []
end

Class Method Details

.for(key, rps_limit) ⇒ Object



8
9
10
11
# File 'lib/rate_limit_mock_server/counter.rb', line 8

def for(key, rps_limit)
  counters[key] ||= Counter.new(rps_limit)
  counters[key]
end

Instance Method Details

#currentObject



25
26
27
# File 'lib/rate_limit_mock_server/counter.rb', line 25

def current
  size
end

#incrementObject



29
30
31
32
33
# File 'lib/rate_limit_mock_server/counter.rb', line 29

def increment
  window << Time.now.to_f
  window.shift while delta && 1.0 < delta
  window.last
end

#increment!Object

Raises:



35
36
37
38
39
40
# File 'lib/rate_limit_mock_server/counter.rb', line 35

def increment!
  increment
  return if current <= rps_limit

  raise RateLimitError.new(rate: current, limit: rps_limit)
end