Module: WithRateLimit

Defined in:
lib/with_rate_limit.rb,
lib/with_rate_limit/cache.rb,
lib/with_rate_limit/version.rb,
lib/with_rate_limit/strategy.rb,
lib/with_rate_limit/cache/redis.rb,
lib/with_rate_limit/cache/memory.rb,
lib/with_rate_limit/strategy/sleep.rb,
lib/with_rate_limit/limit_exceeded_error.rb,
lib/with_rate_limit/strategy/raise_error.rb

Defined Under Namespace

Classes: Cache, LimitExceededError, Strategy

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#with_rate_limit(interval, limit, options = {}, &block) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/with_rate_limit.rb', line 12

def with_rate_limit(interval, limit, options = {}, &block)
  options = default_options(interval, limit).merge(options.transform_keys &:to_sym)
  validate_options(options)
  
  strategy = options[:strategy]
  cache_key = options[:cache_key]
  cache = options[:cache]
  cache_data = cache.get(cache_key).transform_keys(&:to_sym)
  
  last_interval_started_at = cache_data[:last_interval_started_at] || current_timestamp
  operations_count = cache_data[:operations_count].to_i
  timestamp = current_timestamp
  count_reset_delta = timestamp - last_interval_started_at
  interval = interval * 1000

  if (count_reset_delta < interval) && operations_count >= limit
    strategy.execute((interval - count_reset_delta) / 1000.0)
    return with_rate_limit(interval / 1000, limit, options, &block)
  elsif count_reset_delta > interval
    cache.set(cache_key, {last_interval_started_at: timestamp, operations_count: 1})
  else
    cache.set(cache_key, {last_interval_started_at: timestamp, operations_count: operations_count + 1})
  end

  begin
    yield
  rescue StandardError => e
    raise e
  end
end