Class: JSONAPI::NaiveCache
- Inherits:
-
Object
- Object
- JSONAPI::NaiveCache
- Defined in:
- lib/jsonapi/naive_cache.rb
Overview
Cache which memoizes the given block.
It’s “naive” because it clears the least-recently-inserted cache entry rather than the least-recently-used. This makes lookups faster but cache misses more frequent after cleanups. Therefore you the best time to use this cache is when you expect only a small number of unique lookup keys, so that the cache never has to clear.
Also, it’s not thread safe (although jsonapi-resources is careful to only use it in a thread safe way).
Instance Method Summary collapse
- #get(key) ⇒ Object
-
#initialize(cap = 10000, &calculator) ⇒ NaiveCache
constructor
A new instance of NaiveCache.
Constructor Details
#initialize(cap = 10000, &calculator) ⇒ NaiveCache
Returns a new instance of NaiveCache.
14 15 16 17 18 |
# File 'lib/jsonapi/naive_cache.rb', line 14 def initialize(cap = 10000, &calculator) @cap = cap @data = {} @calculator = calculator end |
Instance Method Details
#get(key) ⇒ Object
20 21 22 23 24 25 26 27 28 |
# File 'lib/jsonapi/naive_cache.rb', line 20 def get(key) found = true value = @data.fetch(key) { found = false } return value if found value = @calculator.call(key) @data[key] = value @data.shift if @data.length > @cap return value end |