Class: Rack::Attack::Cache

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store: self.class.default_store) ⇒ Cache

Returns a new instance of Cache.



15
16
17
18
# File 'lib/rack/attack/cache.rb', line 15

def initialize(store: self.class.default_store)
  self.store = store
  @prefix = 'rack::attack'
end

Instance Attribute Details

#last_epoch_timeObject (readonly)

Returns the value of attribute last_epoch_time.



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

def last_epoch_time
  @last_epoch_time
end

#prefixObject

Returns the value of attribute prefix.



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

def prefix
  @prefix
end

#storeObject

Returns the value of attribute store.



20
21
22
# File 'lib/rack/attack/cache.rb', line 20

def store
  @store
end

Class Method Details

.default_storeObject



9
10
11
12
13
# File 'lib/rack/attack/cache.rb', line 9

def self.default_store
  if Object.const_defined?(:Rails) && Rails.respond_to?(:cache)
    ::Rails.cache
  end
end

Instance Method Details

#count(unprefixed_key, period) ⇒ Object



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

def count(unprefixed_key, period)
  key, expires_in = key_and_expiry(unprefixed_key, period)
  do_count(key, expires_in)
end

#delete(unprefixed_key) ⇒ Object



52
53
54
# File 'lib/rack/attack/cache.rb', line 52

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

#read(unprefixed_key) ⇒ Object



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

def read(unprefixed_key)
  enforce_store_presence!
  enforce_store_method_presence!(:read)

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

#reset!Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/rack/attack/cache.rb', line 56

def reset!
  if store.respond_to?(:delete_matched)
    store.delete_matched("#{prefix}*")
  else
    raise(
      Rack::Attack::IncompatibleStoreError,
      "Configured store #{store.class.name} doesn't respond to #delete_matched method"
    )
  end
end

#reset_count(unprefixed_key, period) ⇒ Object



47
48
49
50
# File 'lib/rack/attack/cache.rb', line 47

def reset_count(unprefixed_key, period)
  key, _ = key_and_expiry(unprefixed_key, period)
  store.delete(key)
end

#write(unprefixed_key, value, expires_in) ⇒ Object



43
44
45
# File 'lib/rack/attack/cache.rb', line 43

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