class RSpec::Puppet::Cache

Constants

MAX_ENTRIES

Public Class Methods

new(&default_proc) click to toggle source

@param [Proc] default_proc The default proc to use to fetch objects on cache miss

# File lib/rspec-puppet/cache.rb, line 8
def initialize(&default_proc)
  @default_proc = default_proc
  @cache = {}
  @lra = []
end

Public Instance Methods

get(*args, &blk) click to toggle source
# File lib/rspec-puppet/cache.rb, line 14
def get(*args, &blk)
  key = Marshal.load(Marshal.dump(args))
  if @cache.key?(key)
    # Cache hit
    # move that entry last to make it "most recenty used"
    @lra.insert(-1, @lra.delete_at(@lra.index(args)))
  else
    # Cache miss
    # Ensure room by evicting least recently used if no space left
    expire!
    @cache[args] = (blk || @default_proc).call(*args)
    @lra << args
  end

  @cache[key]
end

Private Instance Methods

expire!() click to toggle source
# File lib/rspec-puppet/cache.rb, line 33
def expire!
  # delete one entry (the oldest) when there is no room in cache
  @cache.delete(@lra.shift) if @cache.size == MAX_ENTRIES
end