Class: LruRedux::Cache

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

Direct Known Subclasses

ThreadSafeCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Cache

Returns a new instance of Cache.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/lru_redux/cache.rb', line 6

def initialize(*args)
  max_size, ignore_nil, _ = args

  max_size ||= 1000
  ignore_nil ||= false

  validate_max_size!(max_size)
  validate_ignore_nil!(ignore_nil)

  @max_size = max_size
  @ignore_nil = ignore_nil
  @data = {}
end

Instance Attribute Details

#ignore_nilObject

Returns the value of attribute ignore_nil.



4
5
6
# File 'lib/lru_redux/cache.rb', line 4

def ignore_nil
  @ignore_nil
end

#max_sizeObject

Returns the value of attribute max_size.



4
5
6
# File 'lib/lru_redux/cache.rb', line 4

def max_size
  @max_size
end

Instance Method Details

#[](key) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/lru_redux/cache.rb', line 66

def [](key)
  key_found = true
  value = @data.delete(key) { key_found = false }
  return unless key_found

  @data[key] = value
end

#[]=(key, val) ⇒ Object



74
75
76
# File 'lib/lru_redux/cache.rb', line 74

def []=(key, val)
  store_item(key, val)
end

#clearObject



102
103
104
# File 'lib/lru_redux/cache.rb', line 102

def clear
  @data.clear
end

#countObject



106
107
108
# File 'lib/lru_redux/cache.rb', line 106

def count
  @data.size
end

#delete(key) ⇒ Object Also known as: evict



92
93
94
# File 'lib/lru_redux/cache.rb', line 92

def delete(key)
  @data.delete(key)
end

#each(&block) ⇒ Object Also known as: each_unsafe



78
79
80
# File 'lib/lru_redux/cache.rb', line 78

def each(&block)
  @data.to_a.reverse_each(&block)
end

#fetch(key) ⇒ Object



55
56
57
58
59
60
61
62
63
64
# File 'lib/lru_redux/cache.rb', line 55

def fetch(key)
  key_found = true
  value = @data.delete(key) { key_found = false }

  if key_found
    @data[key] = value
  else
    yield if block_given? # rubocop:disable Style/IfInsideElse
  end
end

#getset(key) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/lru_redux/cache.rb', line 42

def getset(key)
  key_found = true
  value = @data.delete(key) { key_found = false }

  if key_found
    @data[key] = value
  else
    result = yield
    store_item(key, result)
    result
  end
end

#key?(key) ⇒ Boolean Also known as: has_key?

Returns:

  • (Boolean)


97
98
99
# File 'lib/lru_redux/cache.rb', line 97

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

#to_aObject



84
85
86
# File 'lib/lru_redux/cache.rb', line 84

def to_a
  @data.to_a.reverse
end

#ttl=(_) ⇒ Object



29
30
31
# File 'lib/lru_redux/cache.rb', line 29

def ttl=(_)
  nil
end

#valuesObject



88
89
90
# File 'lib/lru_redux/cache.rb', line 88

def values
  @data.values.reverse
end