Class: RerankerRuby::Cache::Memory

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ttl: 3600) ⇒ Memory

Returns a new instance of Memory.



8
9
10
11
12
# File 'lib/reranker_ruby/cache/memory.rb', line 8

def initialize(ttl: 3600)
  @ttl = ttl
  @store = {}
  @mutex = Mutex.new
end

Instance Attribute Details

#ttl ⇒ Object (readonly)

Returns the value of attribute ttl.



6
7
8
# File 'lib/reranker_ruby/cache/memory.rb', line 6

def ttl
  @ttl
end

Instance Method Details

#clear ⇒ Object



46
47
48
49
50
# File 'lib/reranker_ruby/cache/memory.rb', line 46

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

#get(key) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/reranker_ruby/cache/memory.rb', line 14

def get(key)
  @mutex.synchronize do
    entry = @store[key]
    return nil unless entry

    if Time.now.to_f - entry[:time] > @ttl
      @store.delete(key)
      return nil
    end

    entry[:value]
  end
end

#invalidate(key) ⇒ Object



34
35
36
37
38
# File 'lib/reranker_ruby/cache/memory.rb', line 34

def invalidate(key)
  @mutex.synchronize do
    @store.delete(key)
  end
end

#invalidate_matching(pattern) ⇒ Object



40
41
42
43
44
# File 'lib/reranker_ruby/cache/memory.rb', line 40

def invalidate_matching(pattern)
  @mutex.synchronize do
    @store.delete_if { |k, _| k.match?(pattern) }
  end
end

#prune_expired ⇒ Object



58
59
60
61
62
63
# File 'lib/reranker_ruby/cache/memory.rb', line 58

def prune_expired
  @mutex.synchronize do
    now = Time.now.to_f
    @store.delete_if { |_, entry| now - entry[:time] > @ttl }
  end
end

#set(key, value) ⇒ Object



28
29
30
31
32
# File 'lib/reranker_ruby/cache/memory.rb', line 28

def set(key, value)
  @mutex.synchronize do
    @store[key] = { value: value, time: Time.now.to_f }
  end
end

#size ⇒ Object



52
53
54
55
56
# File 'lib/reranker_ruby/cache/memory.rb', line 52

def size
  @mutex.synchronize do
    @store.size
  end
end