File: options_cache.rb

package info (click to toggle)
ruby-multi-json 1.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 404 kB
  • sloc: ruby: 1,530; makefile: 3
file content (29 lines) | stat: -rw-r--r-- 761 bytes parent folder | download | duplicates (3)
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
module MultiJson
  module OptionsCache
    extend self

    def reset
      @dump_cache = {}
      @load_cache = {}
    end

    def fetch(type, key, &block)
      cache = instance_variable_get("@#{type}_cache")
      cache.key?(key) ? cache[key] : write(cache, key, &block)
    end

    private

    # Normally MultiJson is used with a few option sets for both dump/load
    # methods. When options are generated dynamically though, every call would
    # cause a cache miss and the cache would grow indefinitely. To prevent
    # this, we just reset the cache every time the number of keys outgrows
    # 1000.
    MAX_CACHE_SIZE = 1000

    def write(cache, key)
      cache.clear if cache.length >= MAX_CACHE_SIZE
      cache[key] = yield
    end
  end
end