Class: RateLimit::Window

Inherits:
Object
  • Object
show all
Defined in:
lib/rate_limit/window.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(worker, limit) ⇒ Window

Returns a new instance of Window.



10
11
12
13
# File 'lib/rate_limit/window.rb', line 10

def initialize(worker, limit)
  @worker = worker
  @limit = limit
end

Instance Attribute Details

#limitObject

Returns the value of attribute limit.



5
6
7
# File 'lib/rate_limit/window.rb', line 5

def limit
  @limit
end

#workerObject

Returns the value of attribute worker.



5
6
7
# File 'lib/rate_limit/window.rb', line 5

def worker
  @worker
end

Class Method Details

.clear_cache_counter(windows) ⇒ Object



38
39
40
# File 'lib/rate_limit/window.rb', line 38

def clear_cache_counter(windows)
  Cache.clear(windows.map(&:key))
end

.find_all(topic:, worker:) ⇒ Object



24
25
26
# File 'lib/rate_limit/window.rb', line 24

def find_all(topic:, worker:)
  Limit.fetch(topic).map { |limit| Window.new(worker, limit) }
end

.find_exceeded(windows) ⇒ Object



28
29
30
# File 'lib/rate_limit/window.rb', line 28

def find_exceeded(windows)
  windows.find { |w| w.cached_counter >= w.threshold }
end

.increment_cache_counter(windows) ⇒ Object



32
33
34
35
36
# File 'lib/rate_limit/window.rb', line 32

def increment_cache_counter(windows)
  Cache.write(
    windows.each_with_object({}) { |w, h| h[w.key] = w.interval }
  )
end

Instance Method Details

#cached_counterObject



19
20
21
# File 'lib/rate_limit/window.rb', line 19

def cached_counter
  (Cache.read(key) || 0).to_i
end

#keyObject



15
16
17
# File 'lib/rate_limit/window.rb', line 15

def key
  @key ||= [topic, value, interval].join(':')
end