Class: Moxml::XPath::Cache
- Inherits:
-
Object
- Object
- Moxml::XPath::Cache
- Defined in:
- lib/moxml/xpath/cache.rb
Overview
Simple LRU (Least Recently Used) cache for compiled XPath expressions.
Constant Summary collapse
- DEFAULT_SIZE =
1000
Instance Method Summary collapse
-
#clear ⇒ void
Clears the cache.
-
#get(key) ⇒ Object?
Gets a value from the cache.
-
#get_or_set(key) { ... } ⇒ Object
Gets a value from the cache or sets it using the provided block.
-
#initialize(max_size = DEFAULT_SIZE) ⇒ Cache
constructor
A new instance of Cache.
-
#key?(key) ⇒ Boolean
Checks if a key exists in the cache.
-
#set(key, value) ⇒ Object
Sets a value in the cache.
-
#size ⇒ Integer
Returns the current size of the cache.
Constructor Details
#initialize(max_size = DEFAULT_SIZE) ⇒ Cache
Returns a new instance of Cache.
12 13 14 15 16 |
# File 'lib/moxml/xpath/cache.rb', line 12 def initialize(max_size = DEFAULT_SIZE) @max_size = max_size @cache = {} @access_order = [] end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
Clears the cache.
70 71 72 73 |
# File 'lib/moxml/xpath/cache.rb', line 70 def clear @cache.clear @access_order.clear end |
#get(key) ⇒ Object?
Gets a value from the cache.
59 60 61 62 63 64 65 |
# File 'lib/moxml/xpath/cache.rb', line 59 def get(key) return unless @cache.key?(key) @access_order.delete(key) @access_order.push(key) @cache[key] end |
#get_or_set(key) { ... } ⇒ Object
Gets a value from the cache or sets it using the provided block.
23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/moxml/xpath/cache.rb', line 23 def get_or_set(key) if @cache.key?(key) # Move to end (most recently used) @access_order.delete(key) @access_order.push(key) @cache[key] else value = yield set(key, value) value end end |
#key?(key) ⇒ Boolean
Checks if a key exists in the cache.
86 87 88 |
# File 'lib/moxml/xpath/cache.rb', line 86 def key?(key) @cache.key?(key) end |
#set(key, value) ⇒ Object
Sets a value in the cache.
41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/moxml/xpath/cache.rb', line 41 def set(key, value) if @cache.key?(key) @access_order.delete(key) elsif @cache.size >= @max_size # Remove least recently used lru_key = @access_order.shift @cache.delete(lru_key) end @cache[key] = value @access_order.push(key) value end |
#size ⇒ Integer
Returns the current size of the cache.
78 79 80 |
# File 'lib/moxml/xpath/cache.rb', line 78 def size @cache.size end |