Class: SciYAG::Backends::Cache
- Inherits:
-
Object
- Object
- SciYAG::Backends::Cache
- Defined in:
- lib/SciYAG/Backends/cache.rb
Overview
The Cache class aims at providing a small and easy-to-use cache with validation checking, usage statistics and flushing (automatically removes some entries when it grows too big).
Defined Under Namespace
Classes: CacheEntry
Instance Attribute Summary collapse
-
#statistics ⇒ Object
Records all accessed items and the number of cache misses/succes and so on.
Instance Method Summary collapse
-
#get_cache(name, meta_data, &code) ⇒ Object
Look inside the cache for a cached element.
-
#initialize ⇒ Cache
constructor
Creates a Cache.
-
#stats(name) ⇒ Object
Returns the statistics for the given item, or create them on the fly if necessary:.
Constructor Details
#initialize ⇒ Cache
Creates a Cache
57 58 59 60 61 62 |
# File 'lib/SciYAG/Backends/cache.rb', line 57 def initialize # The cache itself @cache = {} @statistics = {} end |
Instance Attribute Details
#statistics ⇒ Object
Records all accessed items and the number of cache misses/succes and so on.
54 55 56 |
# File 'lib/SciYAG/Backends/cache.rb', line 54 def statistics @statistics end |
Instance Method Details
#get_cache(name, meta_data, &code) ⇒ Object
Look inside the cache for a cached element. If it is found and up-to-date, it is returned. If not, #get_cache runs code, stores its return value as a new cache for (name, meta_data) and returns it.
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/SciYAG/Backends/cache.rb', line 68 def get_cache(name, , &code) if (@cache.key?(name)) and ((cached = @cache[name]).relevant?()) stats(name)[:accesses] += 1 return cached.data elsif @cache.key?(name) stats(name)[:updates] += 1 end stats(name)[:misses] += 1 # Now, we run the code to update the cache entry: data = code.call @cache[name] = CacheEntry.new(name, data, ) return data end |
#stats(name) ⇒ Object
Returns the statistics for the given item, or create them on the fly if necessary:
86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/SciYAG/Backends/cache.rb', line 86 def stats(name) if @statistics[name] return @statistics[name] else @statistics[name] = { :accesses => 0, :misses => 0, :updates => 0 } return @statistics[name] end end |