Class: RedisRateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/redis_rate_limiter.rb,
lib/redis_rate_limiter/version.rb

Constant Summary

VERSION =
'0.0.8'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, redis, options = {}) ⇒ RedisRateLimiter

Initializes a new RedisRateLimiter object



22
23
24
25
26
27
# File 'lib/redis_rate_limiter.rb', line 22

def initialize key, redis, options = {}
  @key      = key
  @redis    = redis
  @limit    = options[:limit] || 50
  @interval = options[:interval] || 60
end

Instance Attribute Details

#intervalInteger



13
# File 'lib/redis_rate_limiter.rb', line 13

attr_accessor :key, :redis, :limit, :interval

#keyString



13
14
15
# File 'lib/redis_rate_limiter.rb', line 13

def key
  @key
end

#limitInteger



13
# File 'lib/redis_rate_limiter.rb', line 13

attr_accessor :key, :redis, :limit, :interval

#redisRedis



13
# File 'lib/redis_rate_limiter.rb', line 13

attr_accessor :key, :redis, :limit, :interval

Instance Method Details

#add(subject, time = Time.now.to_f) ⇒ Object

Add to subject's count



33
34
35
36
37
38
39
40
# File 'lib/redis_rate_limiter.rb', line 33

def add subject, time = Time.now.to_f
  subject = "#{@key}:#{subject}"
  @redis.multi do
    @redis.lpush(subject, time)
    @redis.ltrim(subject, 0, @limit - 1)
    @redis.expire(subject, @interval)
  end
end

#exceeded?(subject) ⇒ Boolean

Check if subject has exceeded count



46
47
48
49
50
51
# File 'lib/redis_rate_limiter.rb', line 46

def exceeded? subject
  subject = "#{@key}:#{subject}"
  return false if @redis.llen(subject) < @limit
  last = @redis.lindex(subject, -1)
  Time.now.to_f - last.to_f < @interval
end