Class: Rollie::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/rollie/rate_limiter.rb

Instance Method Summary collapse

Constructor Details

#initialize(key, options = {}) ⇒ RateLimiter

Create a new RateLimiter instance.

Parameters:

  • key (String)

    A unique name to track this rate limit against.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :limit (Integer)

    The limit

  • :interval (Integer)

    The interval in milliseconds for this rate limit

  • :namespace (String)

    Optional namespace for this rate limit

  • :count_blocked (Boolean)

    if true, all calls to within_limit will count towards total execution count, even if blocked.


15
16
17
18
19
20
# File 'lib/rollie/rate_limiter.rb', line 15

def initialize(key, options = {})
  @key = "#{options[:namespace]}#{key}"
  @limit = options[:limit] || 25
  @interval = (options[:interval] || 1000) * 1000
  @count_blocked = options.key?(:count_blocked) ? options[:count_blocked] : false
end

Instance Method Details

#countInteger

Returns The current count of this RateLimiter.

Returns:

  • (Integer)

    The current count of this RateLimiter.


38
39
40
41
42
43
# File 'lib/rollie/rate_limiter.rb', line 38

def count
  Rollie.redis do |conn|
    range = conn.zrange(@key, 0, -1)
    range.length
  end
end

#within_limitStatus

Executes a block as long as the current rate is within the limit.

Returns:

  • (Status)

    The current status for this RateLimiter.

Raises:

  • (ArgumentError)

25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rollie/rate_limiter.rb', line 25

def within_limit
  raise ArgumentError, 'requires a block' unless block_given?

  Rollie.redis do |conn|
    status = inc(conn)
    unless status.exceeded?
      yield
    end
    status
  end
end