Module: Canon::Cache
- Defined in:
- lib/canon/cache.rb
Overview
Cache for expensive operations during document comparison
Provides thread-safe caching with size limits to prevent memory bloat. Uses LRU (Least Recently Used) eviction when cache is full.
Constant Summary collapse
- MAX_CACHE_SIZE =
Maximum number of entries per cache category
100
Class Method Summary collapse
-
.clear_all ⇒ Object
Clear all caches.
-
.clear_category(category) ⇒ Object
Clear a specific cache category.
-
.fetch(category, key) { ... } ⇒ Object
Fetch a value from cache, or compute and cache it.
-
.key_for_c14n(content, with_comments) ⇒ Object
Generate cache key for XML canonicalization.
-
.key_for_document(content, format, preprocessing) ⇒ Object
Generate cache key for document parsing.
-
.key_for_preprocessing(content, preprocessing) ⇒ Object
Generate cache key for preprocessing.
-
.stats ⇒ Hash
Get cache statistics.
Class Method Details
.clear_all ⇒ Object
Clear all caches
Useful for tests or when memory needs to be freed
60 61 62 63 |
# File 'lib/canon/cache.rb', line 60 def clear_all @caches&.each_value(&:clear) @caches = nil end |
.clear_category(category) ⇒ Object
Clear a specific cache category
68 69 70 71 72 |
# File 'lib/canon/cache.rb', line 68 def clear_category(category) return unless @caches&.key?(category) @caches[category]&.clear end |
.fetch(category, key) { ... } ⇒ Object
Fetch a value from cache, or compute and cache it
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/canon/cache.rb', line 33 def fetch(category, key) cache = cache_for(category) # Check if key exists if cache.key?(key) # Update access time for LRU cache[key][:accessed] = Time.now return cache[key][:value] end # Compute and cache the value value = yield # Evict oldest entry if cache is full if cache.size >= MAX_CACHE_SIZE oldest_key = cache.min_by { |_, v| v[:accessed] }&.first cache.delete(oldest_key) if oldest_key end @clock = (@clock || 0) + 1 cache[key] = { value: value, accessed: @clock } value end |
.key_for_c14n(content, with_comments) ⇒ Object
Generate cache key for XML canonicalization
87 88 89 |
# File 'lib/canon/cache.rb', line 87 def key_for_c14n(content, with_comments) "c14n:#{with_comments}:#{content_hash(content)}" end |
.key_for_document(content, format, preprocessing) ⇒ Object
Generate cache key for document parsing
82 83 84 |
# File 'lib/canon/cache.rb', line 82 def key_for_document(content, format, preprocessing) "doc:#{format}:#{preprocessing}:#{content_hash(content)}" end |
.key_for_preprocessing(content, preprocessing) ⇒ Object
Generate cache key for preprocessing
92 93 94 |
# File 'lib/canon/cache.rb', line 92 def key_for_preprocessing(content, preprocessing) "pre:#{preprocessing}:#{content_hash(content)}" end |
.stats ⇒ Hash
Get cache statistics
77 78 79 |
# File 'lib/canon/cache.rb', line 77 def stats @caches&.transform_values(&:size) || {} end |