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, = {}, &block) = (interval, limit).merge(.transform_keys &:to_sym) () strategy = [:strategy] cache_key = [:cache_key] cache = [:cache] cache_data = cache.get(cache_key).transform_keys(&:to_sym) last_interval_started_at = cache_data[:last_interval_started_at] || operations_count = cache_data[:operations_count].to_i = count_reset_delta = - 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, , &block) elsif count_reset_delta > interval cache.set(cache_key, {last_interval_started_at: , operations_count: 1}) else cache.set(cache_key, {last_interval_started_at: , operations_count: operations_count + 1}) end begin yield rescue StandardError => e raise e end end |