File: cache.rb

package info (click to toggle)
ruby-rspec-puppet 4.0.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,444 kB
  • sloc: ruby: 6,377; makefile: 6
file content (38 lines) | stat: -rw-r--r-- 938 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# frozen_string_literal: true

module RSpec::Puppet
  class Cache
    MAX_ENTRIES = 16

    # @param [Proc] default_proc The default proc to use to fetch objects on cache miss
    def initialize(&default_proc)
      @default_proc = default_proc
      @cache = {}
      @lra = []
    end

    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

    def expire!
      # delete one entry (the oldest) when there is no room in cache
      @cache.delete(@lra.shift) if @cache.size == MAX_ENTRIES
    end
  end
end