Class: GeminiCraft::Cache
- Inherits:
-
Object
- Object
- GeminiCraft::Cache
- Defined in:
- lib/gemini_craft/cache.rb
Overview
Enhanced in-memory cache for API responses with automatic cleanup
Instance Method Summary collapse
-
#cleanup ⇒ Object
Remove expired entries from the cache.
-
#clear ⇒ Object
Clear the entire cache.
-
#get(key) ⇒ String?
Get a value from the cache.
-
#initialize(config) ⇒ Cache
constructor
Initialize the cache.
-
#set(key, value) ⇒ Object
Set a value in the cache.
-
#stats ⇒ Hash
Get cache statistics.
-
#stop_cleanup_thread ⇒ Object
Stop the cleanup thread (for testing).
Constructor Details
#initialize(config) ⇒ Cache
Initialize the cache
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/gemini_craft/cache.rb', line 10 def initialize(config) @config = config @store = {} @timestamps = {} @access_times = {} @mutex = Mutex.new @cleanup_thread = nil start_cleanup_thread if @config.cache_enabled end |
Instance Method Details
#cleanup ⇒ Object
Remove expired entries from the cache
78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/gemini_craft/cache.rb', line 78 def cleanup @mutex.synchronize do current_time = Time.now.to_i expired_keys = [] @timestamps.each do |key, | expired_keys << key if current_time - > @config.cache_ttl end expired_keys.each { |key| remove_entry(key) } expired_keys.size end end |
#clear ⇒ Object
Clear the entire cache
56 57 58 59 60 61 62 |
# File 'lib/gemini_craft/cache.rb', line 56 def clear @mutex.synchronize do @store.clear @timestamps.clear @access_times.clear end end |
#get(key) ⇒ String?
Get a value from the cache
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/gemini_craft/cache.rb', line 24 def get(key) @mutex.synchronize do return nil unless @store.key?(key) # Check if the entry has expired if expired?(key) remove_entry(key) return nil end # Update access time for LRU @access_times[key] = Time.now.to_i @store[key] end end |
#set(key, value) ⇒ Object
Set a value in the cache
43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/gemini_craft/cache.rb', line 43 def set(key, value) @mutex.synchronize do @store[key] = value current_time = Time.now.to_i @timestamps[key] = current_time @access_times[key] = current_time # Perform cleanup if cache is getting large cleanup_if_needed end end |
#stats ⇒ Hash
Get cache statistics
66 67 68 69 70 71 72 73 74 75 |
# File 'lib/gemini_craft/cache.rb', line 66 def stats @mutex.synchronize do { size: @store.size, oldest_entry: @timestamps.values.min, newest_entry: @timestamps.values.max, total_keys: @timestamps.keys } end end |
#stop_cleanup_thread ⇒ Object
Stop the cleanup thread (for testing)
93 94 95 96 97 98 |
# File 'lib/gemini_craft/cache.rb', line 93 def stop_cleanup_thread return unless @cleanup_thread @cleanup_thread.kill @cleanup_thread = nil end |