Class: Rolling::Limit

Inherits:
Object
  • Object
show all
Defined in:
lib/rolling/limit.rb,
lib/rolling/limit/version.rb

Overview

Rolling::Limit is a class that maintains a rolling limit of no more than <max_operations> operations for a given <key> within <timespan> seconds.

Constant Summary collapse

VERSION =
"0.2.0"

Instance Method Summary collapse

Constructor Details

#initialize(redis:, key:, max_operations:, timespan:) ⇒ Limit

Returns a new instance of Limit.



8
9
10
11
12
13
# File 'lib/rolling/limit.rb', line 8

def initialize(redis:, key:, max_operations:, timespan:)
  @redis = redis
  @key = "rlmt:#{key}"
  @timespan = timespan
  @max_operations = max_operations.to_i
end

Instance Method Details

#remainingObject

Increments the counter and returns truthy (with number of remaining operations)



17
18
19
20
21
22
# File 'lib/rolling/limit.rb', line 17

def remaining
  cleanup
  return false if count >= max_operations
  increment
  max_operations - count
end

#remaining?Boolean

Shows numbers of remaining operations without incrementing

Returns:

  • (Boolean)


30
31
32
33
34
# File 'lib/rolling/limit.rb', line 30

def remaining?
  cleanup
  return false if count >= max_operations
  true
end

#reset!Object

Resets this counter



25
26
27
# File 'lib/rolling/limit.rb', line 25

def reset!
  redis.del(key)
end