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.



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

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.



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

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)


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

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