Class: Contrast::Utils::LRUCache

Inherits:
Object
  • Object
show all
Defined in:
lib/contrast/utils/lru_cache.rb

Overview

A LRU(Least Recently Used) Cache store.

Instance Method Summary collapse

Constructor Details

#initialize(capacity = 500) ⇒ LRUCache

Initializes new Least Recently Used Cache Store

Raises:

  • (StandardError)

    raises error if provided capacity is invalid or less or equal to zero



11
12
13
14
15
16
# File 'lib/contrast/utils/lru_cache.rb', line 11

def initialize capacity = 500
  raise(StandardError('Capacity must be bigger than 0')) if capacity <= 0

  @capacity = capacity
  @cache = {}
end

Instance Method Details

#[](key) ⇒ Object



18
19
20
21
22
# File 'lib/contrast/utils/lru_cache.rb', line 18

def [] key
  val = @cache.delete(key)
  @cache[key] = val if val
  val
end

#[]=(key, value) ⇒ Object



24
25
26
27
28
29
# File 'lib/contrast/utils/lru_cache.rb', line 24

def []= key, value
  @cache.delete(key)
  @cache[key] = value
  @cache.shift if @cache.size > @capacity
  value # rubocop:disable Lint/Void
end

#clearObject



43
44
45
# File 'lib/contrast/utils/lru_cache.rb', line 43

def clear
  @cache.clear
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/contrast/utils/lru_cache.rb', line 35

def key? key
  @cache.key?(key)
end

#keysObject



31
32
33
# File 'lib/contrast/utils/lru_cache.rb', line 31

def keys
  @cache.keys
end

#valuesObject



39
40
41
# File 'lib/contrast/utils/lru_cache.rb', line 39

def values
  @cache.values
end