Class: Senko::Cache

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

Instance Method Summary collapse

Constructor Details

#initialize(max_size: 256) ⇒ Cache

Returns a new instance of Cache.



5
6
7
8
9
10
# File 'lib/senko/cache.rb', line 5

def initialize(max_size: 256)
  @store = {}
  @max_size = max_size
  @access_order = []
  @mutex = Mutex.new
end

Instance Method Details

#clearObject



36
37
38
39
40
41
# File 'lib/senko/cache.rb', line 36

def clear
  @mutex.synchronize do
    @store.clear
    @access_order.clear
  end
end

#fetch(key) ⇒ Object



29
30
31
32
33
34
# File 'lib/senko/cache.rb', line 29

def fetch(key)
  cached = get(key)
  return cached if cached

  put(key, yield)
end

#get(key) ⇒ Object



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

def get(key)
  @mutex.synchronize do
    value = @store[key]
    touch(key) if value
    value
  end
end

#put(key, value) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/senko/cache.rb', line 20

def put(key, value)
  @mutex.synchronize do
    evict_lru if @store.size >= @max_size && !@store.key?(key)
    @store[key] = value
    touch(key)
  end
  value
end