Class: Proxy::OpenBolt::LruCache
- Inherits:
-
Object
- Object
- Proxy::OpenBolt::LruCache
- Defined in:
- lib/smart_proxy_openbolt/lru_cache.rb
Overview
Thread-safe, size-bounded cache that evicts the least recently used entry when full. Built on Ruby’s insertion-ordered Hash. Implemented here rather than pulling in a gem to avoid adding packaging dependencies for something this straightforward.
Instance Method Summary collapse
- #delete(key) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(max_size) ⇒ LruCache
constructor
A new instance of LruCache.
- #key?(key) ⇒ Boolean
- #put(key, value) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(max_size) ⇒ LruCache
Returns a new instance of LruCache.
7 8 9 10 11 12 |
# File 'lib/smart_proxy_openbolt/lru_cache.rb', line 7 def initialize(max_size) raise ArgumentError, 'max_size must be at least 1' if max_size < 1 @max_size = max_size @hash = {} @mutex = Mutex.new end |
Instance Method Details
#delete(key) ⇒ Object
31 32 33 |
# File 'lib/smart_proxy_openbolt/lru_cache.rb', line 31 def delete(key) @mutex.synchronize { @hash.delete(key) } end |
#get(key) ⇒ Object
14 15 16 17 18 19 20 21 |
# File 'lib/smart_proxy_openbolt/lru_cache.rb', line 14 def get(key) @mutex.synchronize do return nil unless @hash.key?(key) # Move to end (most recently used) value = @hash.delete(key) @hash[key] = value end end |
#key?(key) ⇒ Boolean
35 36 37 |
# File 'lib/smart_proxy_openbolt/lru_cache.rb', line 35 def key?(key) @mutex.synchronize { @hash.key?(key) } end |
#put(key, value) ⇒ Object
23 24 25 26 27 28 29 |
# File 'lib/smart_proxy_openbolt/lru_cache.rb', line 23 def put(key, value) @mutex.synchronize do @hash.delete(key) if @hash.key?(key) @hash[key] = value @hash.shift if @hash.size > @max_size end end |
#size ⇒ Object
39 40 41 |
# File 'lib/smart_proxy_openbolt/lru_cache.rb', line 39 def size @mutex.synchronize { @hash.size } end |