Class: ParamsReady::Helpers::Memo

Inherits:
Object
  • Object
show all
Defined in:
lib/params_ready/helpers/memo.rb

Instance Method Summary collapse

Constructor Details

#initialize(slots = 1) ⇒ Memo

Returns a new instance of Memo.

Raises:



9
10
11
12
13
# File 'lib/params_ready/helpers/memo.rb', line 9

def initialize(slots = 1)
  raise ParamsReadyError, "Expected positive value for number of slots, got: '#{slots}'" unless slots > 0
  @slots = slots
  @cache = nil
end

Instance Method Details

#cache_value(value, key) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/params_ready/helpers/memo.rb', line 23

def cache_value(value, key)
  stale = @cache
  return if stale&.key? key

  frozen = Extensions::Hash.try_deep_freeze(value)

  fresh = if stale.nil? || @slots == 1
    { key => frozen }
  else
    kept = stale.to_a.last(@slots - 1)

    [*kept, [key, frozen]].to_h
  end

  @cache = fresh.freeze
end

#cached_value(key) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/params_ready/helpers/memo.rb', line 15

def cached_value(key)
  cache = @cache
  return Extensions::Undefined if cache.nil?
  return Extensions::Undefined unless cache.key? key

  cache[key]
end