Class: Desiru::Cache

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

Overview

Thread-safe in-memory cache with TTL support and LRU eviction

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(max_size: 1000, cleanup_interval: 300) ⇒ Cache

Returns a new instance of Cache.



8
9
10
11
12
13
14
# File 'lib/desiru/cache.rb', line 8

def initialize(max_size: 1000, cleanup_interval: 300)
  @store = {}
  @mutex = Mutex.new
  @max_size = max_size
  @cleanup_interval = cleanup_interval
  @last_cleanup = Time.now
end

Instance Method Details

#cleanup_expiredObject

Manually trigger cleanup of expired entries



95
96
97
98
99
# File 'lib/desiru/cache.rb', line 95

def cleanup_expired
  @mutex.synchronize do
    @store.delete_if { |_, entry| entry.expires_at <= Time.now }
  end
end

#clearObject

Clear all entries



81
82
83
84
85
# File 'lib/desiru/cache.rb', line 81

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

#delete(key) ⇒ Object

Delete a key from cache



74
75
76
77
78
# File 'lib/desiru/cache.rb', line 74

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

#get(key) ⇒ Object

Get a value from cache without setting



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/desiru/cache.rb', line 44

def get(key)
  @mutex.synchronize do
    if (entry = @store[key])
      if entry.expires_at > Time.now
        entry.accessed_at = Time.now
        entry.value
      else
        @store.delete(key)
        nil
      end
    end
  end
end

#get_or_set(key, ttl: 3600) ⇒ Object

Get a value from cache or set it using the provided block



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/desiru/cache.rb', line 17

def get_or_set(key, ttl: 3600)
  @mutex.synchronize do
    cleanup_if_needed

    if (entry = @store[key])
      if entry.expires_at > Time.now
        entry.accessed_at = Time.now
        return entry.value
      else
        @store.delete(key)
      end
    end

    # Evict LRU if at capacity
    evict_lru if @store.size >= @max_size

    value = yield
    @store[key] = Entry.new(
      value: value,
      expires_at: Time.now + ttl,
      accessed_at: Time.now
    )
    value
  end
end

#set(key, value, ttl: 3600) ⇒ Object

Set a value in cache



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/desiru/cache.rb', line 59

def set(key, value, ttl: 3600)
  @mutex.synchronize do
    cleanup_if_needed
    evict_lru if @store.size >= @max_size && !@store.key?(key)

    @store[key] = Entry.new(
      value: value,
      expires_at: Time.now + ttl,
      accessed_at: Time.now
    )
    value
  end
end

#sizeObject

Get the current size



88
89
90
91
92
# File 'lib/desiru/cache.rb', line 88

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