Class: Rack::Attack::StoreProxy::RedisProxy

Inherits:
BaseProxy
  • Object
show all
Defined in:
lib/rack/attack/store_proxy/redis_proxy.rb

Direct Known Subclasses

RedisStoreProxy

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseProxy

inherited, lookup, proxies

Constructor Details

#initialize(*args) ⇒ RedisProxy

Returns a new instance of RedisProxy.



9
10
11
12
13
14
15
# File 'lib/rack/attack/store_proxy/redis_proxy.rb', line 9

def initialize(*args)
  if Gem::Version.new(Redis::VERSION) < Gem::Version.new("3")
    warn 'RackAttack requires Redis gem >= 3.0.0.'
  end

  super(*args)
end

Class Method Details

.handle?(store) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/rack/attack/store_proxy/redis_proxy.rb', line 17

def self.handle?(store)
  defined?(::Redis) && store.class == ::Redis
end

Instance Method Details

#delete(key, _options = {}) ⇒ Object



42
43
44
# File 'lib/rack/attack/store_proxy/redis_proxy.rb', line 42

def delete(key, _options = {})
  rescuing { del(key) }
end

#delete_matched(matcher, _options = nil) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rack/attack/store_proxy/redis_proxy.rb', line 46

def delete_matched(matcher, _options = nil)
  cursor = "0"

  rescuing do
    # Fetch keys in batches using SCAN to avoid blocking the Redis server.
    loop do
      cursor, keys = scan(cursor, match: matcher, count: 1000)
      del(*keys) unless keys.empty?
      break if cursor == "0"
    end
  end
end

#increment(key, amount, options = {}) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/rack/attack/store_proxy/redis_proxy.rb', line 33

def increment(key, amount, options = {})
  rescuing do
    pipelined do |redis|
      redis.incrby(key, amount)
      redis.expire(key, options[:expires_in]) if options[:expires_in]
    end.first
  end
end

#read(key) ⇒ Object



21
22
23
# File 'lib/rack/attack/store_proxy/redis_proxy.rb', line 21

def read(key)
  rescuing { get(key) }
end

#write(key, value, options = {}) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/rack/attack/store_proxy/redis_proxy.rb', line 25

def write(key, value, options = {})
  if (expires_in = options[:expires_in])
    rescuing { setex(key, expires_in, value) }
  else
    rescuing { set(key, value) }
  end
end