Sha256: 911772c0e5ec053903ee17eae13f6f6254efbe4f344fb9a9ffc8456fc402ce37

Contents?: true

Size: 824 Bytes

Versions: 7

Compression:

Stored size: 824 Bytes

Contents

# Based on code by Sam Saffron: https://stackoverflow.com/a/16161783/181916
module Skylight
  module Util
    class LruCache
      def initialize(max_size)
        @max_size = max_size
        @data = {}
      end

      def max_size=(size)
        raise ArgumentError, :max_size if @max_size < 1

        @max_size = size
        @data.shift while @data.size > @max_size
      end

      # Individual hash operations here are atomic in MRI.
      def fetch(key)
        found = true
        value = @data.delete(key) { found = false }

        if !found && block_given?
          value = yield
        end

        @data[key] = value if value

        if !found && value && @data.length > @max_size
          @data.shift
        end

        value
      end

      def clear
        @data.clear
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
skylight-5.1.0.beta lib/skylight/util/lru_cache.rb
skylight-5.0.1 lib/skylight/util/lru_cache.rb
skylight-5.0.0 lib/skylight/util/lru_cache.rb
skylight-5.0.0.beta5 lib/skylight/util/lru_cache.rb
skylight-5.0.0.beta4 lib/skylight/util/lru_cache.rb
skylight-5.0.0.beta3 lib/skylight/util/lru_cache.rb
skylight-5.0.0.beta2 lib/skylight/util/lru_cache.rb