Method: Istox::RateLimit#initialize

Defined in:
lib/istox/helpers/rate_limit.rb

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

Create a Ratelimit object.

Cannot be larger than the bucket_span.

Parameters:

  • key (String)

    A name to uniquely identify this rate limit. For example, ‘emails’

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

    Options hash

Options Hash (options):

  • :bucket_span (Integer) — default: 600

    Time span to track in seconds

  • :bucket_interval (Integer) — default: 5

    How many seconds each bucket represents

  • :bucket_expiry (Integer) — default: @bucket_span

    How long we keep data in each bucket before it is auto expired.

  • :redis (Redis) — default: nil

    Redis client if you need to customize connection options

Raises:

  • (ArgumentError)


20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/istox/helpers/rate_limit.rb', line 20

def initialize(key, options = {})
  @key = key
  raise ArgumentError, 'Redis object is now passed in via the options hash - options[:redis]' unless options.is_a?(Hash)

  @bucket_span = options[:bucket_span] || 600
  @bucket_interval = options[:bucket_interval] || 5
  @bucket_expiry = options[:bucket_expiry] || @bucket_span
  raise ArgumentError, 'Bucket expiry cannot be larger than the bucket span' if @bucket_expiry > @bucket_span

  @bucket_count = (@bucket_span / @bucket_interval).round
  raise ArgumentError, 'Cannot have less than 3 buckets' if @bucket_count < 3

  @raw_redis = options[:redis]
end