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 17 18 19 20 |
# File 'lib/moxml/xpath/cache.rb', line 12 def initialize(max_size = DEFAULT_SIZE) @max_size = max_size # One insertion-ordered hash: re-inserting a key on access # makes the first entry the least-recently-used. An # Array-backed order list cost ~600ns per hit in O(n) # deletes — the adapter's xpath path hits three caches per # call. @entries = {} end |
Instance Method Details
#clear ⇒ void
This method returns an undefined value.
Clears the cache.
64 65 66 |
# File 'lib/moxml/xpath/cache.rb', line 64 def clear @entries.clear end |
#get(key) ⇒ Object?
Gets a value from the cache.
54 55 56 57 58 59 |
# File 'lib/moxml/xpath/cache.rb', line 54 def get(key) return unless @entries.key?(key) value = @entries.delete(key) @entries[key] = value end |
#get_or_set(key) { ... } ⇒ Object
Gets a value from the cache or sets it using the provided block.
27 28 29 30 31 32 33 34 35 36 |
# File 'lib/moxml/xpath/cache.rb', line 27 def get_or_set(key) if @entries.key?(key) value = @entries.delete(key) @entries[key] = value else value = yield set(key, value) value end end |
#key?(key) ⇒ Boolean
Checks if a key exists in the cache.
79 80 81 |
# File 'lib/moxml/xpath/cache.rb', line 79 def key?(key) @entries.key?(key) end |
#set(key, value) ⇒ Object
Sets a value in the cache.
43 44 45 46 47 48 |
# File 'lib/moxml/xpath/cache.rb', line 43 def set(key, value) @entries.delete(key) @entries[key] = value @entries.shift if @entries.size > @max_size value end |
#size ⇒ Integer
Returns the current size of the cache.
71 72 73 |
# File 'lib/moxml/xpath/cache.rb', line 71 def size @entries.size end |