Class: BetterTranslate::Cache
- Inherits:
-
Object
- Object
- BetterTranslate::Cache
- Defined in:
- lib/better_translate/cache.rb
Overview
LRU (Least Recently Used) Cache implementation
Thread-safe cache with configurable capacity and optional TTL.
Instance Attribute Summary collapse
-
#capacity ⇒ Integer
readonly
Maximum number of items in cache.
-
#ttl ⇒ Integer?
readonly
Time to live in seconds.
Instance Method Summary collapse
-
#clear ⇒ void
Clear the cache.
-
#get(key) ⇒ String?
Get a value from the cache.
-
#initialize(capacity: 1000, ttl: nil) ⇒ Cache
constructor
Initialize a new cache.
-
#key?(key) ⇒ Boolean
Check if key exists in cache.
-
#set(key, value) ⇒ String
Set a value in the cache.
-
#size ⇒ Integer
Get cache size.
Constructor Details
#initialize(capacity: 1000, ttl: nil) ⇒ Cache
Initialize a new cache
33 34 35 36 37 38 |
# File 'lib/better_translate/cache.rb', line 33 def initialize(capacity: 1000, ttl: nil) @capacity = capacity @ttl = ttl @cache = {} @mutex = Mutex.new end |
Instance Attribute Details
#capacity ⇒ Integer (readonly)
Returns Maximum number of items in cache.
20 21 22 |
# File 'lib/better_translate/cache.rb', line 20 def capacity @capacity end |
#ttl ⇒ Integer? (readonly)
Returns Time to live in seconds.
23 24 25 |
# File 'lib/better_translate/cache.rb', line 23 def ttl @ttl end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
Clear the cache
97 98 99 |
# File 'lib/better_translate/cache.rb', line 97 def clear @mutex.synchronize { @cache.clear } end |
#get(key) ⇒ String?
Get a value from the cache
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/better_translate/cache.rb', line 48 def get(key) @mutex.synchronize do return nil unless @cache.key?(key) entry = @cache[key] # Check TTL ttl_value = @ttl if ttl_value && entry && Time.now - entry[:timestamp] > ttl_value @cache.delete(key) return nil end # Move to end (most recently used) @cache.delete(key) @cache[key] = entry entry[:value] end end |
#key?(key) ⇒ Boolean
Check if key exists in cache
122 123 124 |
# File 'lib/better_translate/cache.rb', line 122 def key?(key) !get(key).nil? end |
#set(key, value) ⇒ String
Set a value in the cache
77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/better_translate/cache.rb', line 77 def set(key, value) @mutex.synchronize do # Remove oldest entry if at capacity @cache.shift if @cache.size >= @capacity && !@cache.key?(key) @cache[key] = { value: value, timestamp: Time.now } value end end |
#size ⇒ Integer
Get cache size
108 109 110 |
# File 'lib/better_translate/cache.rb', line 108 def size @mutex.synchronize { @cache.size } end |