Class: Enumpath::PathCache
- Inherits:
-
Object
- Object
- Enumpath::PathCache
- Defined in:
- lib/enumpath/path_cache.rb
Overview
A small cache of normalized path expressions. It is guarded by a mutex, so threads can share it, and it holds at
most max_size entries: when it is full the least recently used entry is dropped, so a long-running process that
applies many distinct dynamic paths does not grow without limit.
Constant Summary collapse
- DEFAULT_MAX_SIZE =
The number of entries kept when no size is given
1_000
Instance Attribute Summary collapse
-
#max_size ⇒ Integer
readonly
The most entries the cache keeps.
Instance Method Summary collapse
-
#get(key) ⇒ Object
The cached value, or nil if there is none.
-
#get_or_set(key) {|key| ... } ⇒ Object
Returns the cached value for the key.
-
#initialize(max_size = DEFAULT_MAX_SIZE) ⇒ PathCache
constructor
A new instance of PathCache.
-
#reset ⇒ void
Removes every entry.
-
#set(key, value) ⇒ Object
The value.
-
#size ⇒ Integer
The number of entries.
Constructor Details
#initialize(max_size = DEFAULT_MAX_SIZE) ⇒ PathCache
Returns a new instance of PathCache.
16 17 18 19 20 21 22 |
# File 'lib/enumpath/path_cache.rb', line 16 def initialize(max_size = DEFAULT_MAX_SIZE) raise ArgumentError, "max_size must be a positive Integer, got #{max_size.inspect}" unless valid_size?(max_size) @max_size = max_size @data = {} @mutex = Mutex.new end |
Instance Attribute Details
#max_size ⇒ Integer (readonly)
Returns the most entries the cache keeps.
12 13 14 |
# File 'lib/enumpath/path_cache.rb', line 12 def max_size @max_size end |
Instance Method Details
#get(key) ⇒ Object
Returns the cached value, or nil if there is none. A hit counts as a use.
26 27 28 29 |
# File 'lib/enumpath/path_cache.rb', line 26 def get(key) key = key.to_s @mutex.synchronize { touch(key) ? @data[key] : nil } end |
#get_or_set(key) {|key| ... } ⇒ Object
Returns the cached value for the key. When there is none, calls the block with the key, stores its result and returns that. Two threads that miss at the same time may both call the block; the last result is kept.
45 46 47 48 49 50 51 |
# File 'lib/enumpath/path_cache.rb', line 45 def get_or_set(key) key = key.to_s hit, value = @mutex.synchronize { touch(key) ? [true, @data[key]] : [false, nil] } return value if hit @mutex.synchronize { store(key, yield(key)) } end |
#reset ⇒ void
This method returns an undefined value.
Removes every entry
56 57 58 59 |
# File 'lib/enumpath/path_cache.rb', line 56 def reset @mutex.synchronize { @data.clear } nil end |
#set(key, value) ⇒ Object
Returns the value.
34 35 36 37 |
# File 'lib/enumpath/path_cache.rb', line 34 def set(key, value) key = key.to_s @mutex.synchronize { store(key, value) } end |
#size ⇒ Integer
Returns the number of entries.
62 63 64 |
# File 'lib/enumpath/path_cache.rb', line 62 def size @mutex.synchronize { @data.size } end |