Class: HolidayCo::Cache

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

Overview

A tiny thread-safe LRU cache used to memoize per-year holiday calculations, so holidays are only ever calculated once per year per process.

Constant Summary collapse

DEFAULT_MAX_SIZE =
64

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size: DEFAULT_MAX_SIZE) ⇒ Cache

Returns a new instance of Cache.

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
# File 'lib/holiday_co/cache.rb', line 11

def initialize(max_size: DEFAULT_MAX_SIZE)
  raise ArgumentError, "max_size must be a positive integer" unless max_size.is_a?(Integer) && max_size.positive?

  @max_size = max_size
  @store = {}
  @mutex = Mutex.new
end

Instance Attribute Details

#max_sizeObject (readonly)

Returns the value of attribute max_size.



9
10
11
# File 'lib/holiday_co/cache.rb', line 9

def max_size
  @max_size
end

Instance Method Details

#clear!Object



37
38
39
40
# File 'lib/holiday_co/cache.rb', line 37

def clear!
  @mutex.synchronize { @store.clear }
  nil
end

#fetch(key) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/holiday_co/cache.rb', line 19

def fetch(key)
  @mutex.synchronize do
    if @store.key?(key)
      # Re-insert on hit so insertion order tracks recency.
      @store[key] = @store.delete(key)
    else
      value = yield
      @store[key] = value
      @store.shift while @store.size > @max_size
      value
    end
  end
end

#sizeObject



33
34
35
# File 'lib/holiday_co/cache.rb', line 33

def size
  @mutex.synchronize { @store.size }
end