class Nutrella::Cache
Provides a cache of the most recently used items.
Attributes
capacity[R]
path[R]
Public Class Methods
new(path, capacity)
click to toggle source
# File lib/nutrella/cache.rb, line 12 def initialize(path, capacity) @path = path @capacity = capacity end
Public Instance Methods
fetch(key) { || ... }
click to toggle source
# File lib/nutrella/cache.rb, line 17 def fetch(key) value = lookup(key) || yield write(key, value) value end
search(search_reg_exp)
click to toggle source
# File lib/nutrella/cache.rb, line 23 def search(search_reg_exp) cache_contents.find { |k, _v| search_reg_exp.match?(k) }.last rescue nil end
Private Instance Methods
cache_contents()
click to toggle source
# File lib/nutrella/cache.rb, line 49 def cache_contents @_cache_contents ||= begin YAML.load_file(path) rescue nil end end
cached_entries(key, value)
click to toggle source
# File lib/nutrella/cache.rb, line 41 def cached_entries(key, value) entries = cache_contents.reject { |k, _v| k == key } [[key, value]].concat(entries).take(capacity) rescue [[key, value]] end
lookup(key)
click to toggle source
# File lib/nutrella/cache.rb, line 31 def lookup(key) cache_contents.find { |k, _v| k == key }.last rescue nil end
write(key, value)
click to toggle source
# File lib/nutrella/cache.rb, line 37 def write(key, value) File.write(path, cached_entries(key, value).to_yaml) end