Class: SpeedLimiter::Redis

Inherits:
Object
  • Object
show all
Defined in:
lib/speed_limiter/redis.rb

Overview

Redis wrapper

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis) ⇒ Redis

Returns a new instance of Redis.



6
7
8
# File 'lib/speed_limiter/redis.rb', line 6

def initialize(redis)
  @redis = redis
end

Instance Attribute Details

#redisObject (readonly)

Returns the value of attribute redis.



9
10
11
# File 'lib/speed_limiter/redis.rb', line 9

def redis
  @redis
end

Instance Method Details

#increment(key, period) ⇒ Object

rubocop:disable Metrics/MethodLength



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/speed_limiter/redis.rb', line 15

def increment(key, period) # rubocop:disable Metrics/MethodLength
  if supports_expire_nx?
    count, ttl = redis.pipelined do |pipeline|
      pipeline.incrby(key, 1)
      pipeline.call(:expire, key, period.to_i, "NX")
    end
  else
    count, ttl = redis.pipelined do |pipeline|
      pipeline.incrby(key, 1)
      pipeline.ttl(key)
    end
    redis.expire(key, period.to_i) if ttl.negative?
  end

  [count, ttl]
end

#ttl(key) ⇒ Object



11
12
13
# File 'lib/speed_limiter/redis.rb', line 11

def ttl(key)
  redis.pttl(key) / 1000.0
end