Class: Smplkit::Flags::ResolutionCache

Inherits:
Object
  • Object
show all
Defined in:
lib/smplkit/flags/client.rb

Overview

Thread-safe LRU resolution cache with hit/miss stats.

Constant Summary collapse

DEFAULT_MAX_SIZE =
10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size: DEFAULT_MAX_SIZE) ⇒ ResolutionCache

Returns a new instance of ResolutionCache.



62
63
64
65
66
67
68
# File 'lib/smplkit/flags/client.rb', line 62

def initialize(max_size: DEFAULT_MAX_SIZE)
  @max_size = max_size
  @cache = {}
  @lock = Mutex.new
  @cache_hits = 0
  @cache_misses = 0
end

Instance Attribute Details

#cache_hitsObject (readonly)

Returns the value of attribute cache_hits.



60
61
62
# File 'lib/smplkit/flags/client.rb', line 60

def cache_hits
  @cache_hits
end

#cache_missesObject (readonly)

Returns the value of attribute cache_misses.



60
61
62
# File 'lib/smplkit/flags/client.rb', line 60

def cache_misses
  @cache_misses
end

Instance Method Details

#clearObject



93
94
95
# File 'lib/smplkit/flags/client.rb', line 93

def clear
  @lock.synchronize { @cache.clear }
end

#get(cache_key) ⇒ Object

Return [hit, value]. Moves the key to end on hit.



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/smplkit/flags/client.rb', line 71

def get(cache_key)
  @lock.synchronize do
    if @cache.key?(cache_key)
      value = @cache.delete(cache_key)
      @cache[cache_key] = value
      @cache_hits += 1
      [true, value]
    else
      @cache_misses += 1
      [false, nil]
    end
  end
end

#put(cache_key, value) ⇒ Object



85
86
87
88
89
90
91
# File 'lib/smplkit/flags/client.rb', line 85

def put(cache_key, value)
  @lock.synchronize do
    @cache.delete(cache_key) if @cache.key?(cache_key)
    @cache[cache_key] = value
    @cache.shift while @cache.size > @max_size
  end
end