rack-attack/lib/rack/attack/cache.rb
Aaron Suggs e7aa5f4abe Use rotating cache keys for throttle (instead of expiring)
Throttles use a cache key with a timestamp (Time.now.to_i/period), so a
new cache key is used for each period.

No longer set an explicit expiry on each cache key (though it may
inherit a default expiry from the cache store).

Also, set env['rack.attack.throttle_data'] with info about incremented
(but not necessarily exceeded) throttles.
2012-08-08 14:59:42 -04:00

23 lines
543 B
Ruby

module Rack
module Attack
class Cache
attr_accessor :store, :prefix
def initialize
@store = ::Rails.cache if defined?(::Rails.cache)
@prefix = 'rack::attack'
end
def count(unprefixed_key, period)
key = "#{prefix}:#{Time.now.to_i/period}:#{unprefixed_key}"
result = store.increment(key, 1)
# NB: Some stores return nil when incrementing uninitialized values
if result.nil?
store.write(key, 1)
end
result || 1
end
end
end
end