Sha256: 6eaeaf3a17bfde1dec3838329117eaf61832a06470bac46d5210a4ea43573340
Contents?: true
Size: 816 Bytes
Versions: 9
Compression:
Stored size: 816 Bytes
Contents
require "yaml" module Nutrella # # Provides a cache of the most recently used items. # class Cache attr_reader :capacity, :path def initialize(path, capacity) @path = path @capacity = capacity end def fetch(key) value = lookup(key) || yield write(key, value) value end private def lookup(key) cache_contents.find { |k, _v| k == key }.last rescue nil end def write(key, value) File.write(path, cached_entries(key, value).to_yaml) end def cached_entries(key, value) entries = cache_contents.reject { |k, _v| k == key } [[key, value]].concat(entries).take(capacity) rescue [[key, value]] end def cache_contents @cache_contents ||= YAML.load_file(path) end end end
Version data entries
9 entries across 9 versions & 1 rubygems