Class: OpenTelemetry::Instrumentation::PG::LruCache
- Inherits:
-
Object
- Object
- OpenTelemetry::Instrumentation::PG::LruCache
- Defined in:
- lib/opentelemetry/instrumentation/pg/lru_cache.rb
Overview
A simple LRU cache for the postgres instrumentation.
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
-
#initialize(size) ⇒ LruCache
constructor
Rather than take a dependency on another gem, we implement a very, very basic LRU cache here.
Constructor Details
#initialize(size) ⇒ LruCache
Rather than take a dependency on another gem, we implement a very, very basic LRU cache here. We can take advantage of the fact that Ruby hashes are ordered to always keep the recently-accessed keys at the top.
15 16 17 18 19 20 |
# File 'lib/opentelemetry/instrumentation/pg/lru_cache.rb', line 15 def initialize(size) raise ArgumentError, 'Invalid size' if size < 1 @limit = size @store = {} end |
Instance Method Details
#[](key) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/opentelemetry/instrumentation/pg/lru_cache.rb', line 22 def [](key) # We need to check for the key explicitly, because `nil` is a valid hash value. return unless @store.key?(key) # Since the cache contains the item, we delete and re-insert into the hash. # This guarantees that hash keys are ordered by access recency. value = @store.delete(key) @store[key] = value value end |
#[]=(key, value) ⇒ Object
34 35 36 37 38 39 40 |
# File 'lib/opentelemetry/instrumentation/pg/lru_cache.rb', line 34 def []=(key, value) # We remove the value if it's already present, so that the hash keys remain ordered # by access recency. @store.delete(key) @store[key] = value @store.shift if @store.length > @limit end |