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

Version Path
nutrella-1.2.0 lib/nutrella/cache.rb
nutrella-1.1.0 lib/nutrella/cache.rb
nutrella-1.0.0 lib/nutrella/cache.rb
nutrella-0.9.0 lib/nutrella/cache.rb
nutrella-0.8.0 lib/nutrella/cache.rb
nutrella-0.7.0 lib/nutrella/cache.rb
nutrella-0.6.0 lib/nutrella/cache.rb
nutrella-0.5.0 lib/nutrella/cache.rb
nutrella-0.4.0 lib/nutrella/cache.rb