Sha256: 9fc8036aff7d88ee88d6fba760bda85090b102f44f49b10097399e0d42f9ee91

Contents?: true

Size: 915 Bytes

Versions: 43

Compression:

Stored size: 915 Bytes

Contents

module JSONAPI

  # Cache which memoizes the given block.
  #
  # It's "naive" because it clears the least-recently-inserted cache entry
  # rather than the least-recently-used. This makes lookups faster but cache
  # misses more frequent after cleanups. Therefore you the best time to use
  # this cache is when you expect only a small number of unique lookup keys, so
  # that the cache never has to clear.
  #
  # Also, it's not thread safe (although jsonapi-resources is careful to only
  # use it in a thread safe way).
  class NaiveCache
    def initialize(cap = 10000, &calculator)
      @cap = cap
      @data = {}
      @calculator = calculator
    end

    def get(key)
      found = true
      value = @data.fetch(key) { found = false }
      return value if found
      value = @calculator.call(key)
      @data[key] = value
      @data.shift if @data.length > @cap
      return value
    end
  end
end

Version data entries

43 entries across 43 versions & 1 rubygems

Version Path
jsonapi-resources-0.10.7 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.6 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.5 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.4 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.9.12 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.3 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.2 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.9.11 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.1 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.0 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.0.beta9 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.0.beta8 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.0.beta7 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.0.beta6 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.9.10 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.9.9 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.0.beta5 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.9.8 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.10.0.beta4 lib/jsonapi/naive_cache.rb
jsonapi-resources-0.9.7 lib/jsonapi/naive_cache.rb