Class: Rack::Attack::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/attack/cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



7
8
9
10
# File 'lib/rack/attack/cache.rb', line 7

def initialize
  self.store = ::Rails.cache if defined?(::Rails.cache)
  @prefix = 'rack::attack'
end

Instance Attribute Details

#prefixObject

Returns the value of attribute prefix.



5
6
7
# File 'lib/rack/attack/cache.rb', line 5

def prefix
  @prefix
end

#storeObject

Returns the value of attribute store.



12
13
14
# File 'lib/rack/attack/cache.rb', line 12

def store
  @store
end

Instance Method Details

#count(unprefixed_key, period) ⇒ Object



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

def count(unprefixed_key, period)
  epoch_time = Time.now.to_i
  # Add 1 to expires_in to avoid timing error: http://git.io/i1PHXA
  expires_in = period - (epoch_time % period) + 1
  do_count(build_key(unprefixed_key, period), expires_in)
end

#get_count(unprefixed_key, period) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/rack/attack/cache.rb', line 17

def get_count(unprefixed_key, period)
  if store.class == Rack::Attack::StoreProxy::RedisStoreProxy
    store.raw_read(build_key(unprefixed_key, period))
  else
    store.read(build_key(unprefixed_key, period))
  end
end

#read(unprefixed_key) ⇒ Object



32
33
34
# File 'lib/rack/attack/cache.rb', line 32

def read(unprefixed_key)
  store.read("#{prefix}:#{unprefixed_key}")
end

#write(unprefixed_key, value, expires_in) ⇒ Object



36
37
38
# File 'lib/rack/attack/cache.rb', line 36

def write(unprefixed_key, value, expires_in)
  store.write("#{prefix}:#{unprefixed_key}", value, :expires_in => expires_in)
end