Module: Fontist::Memoizable::ClassMethods

Defined in:
lib/fontist/memoizable.rb

Instance Method Summary collapse

Instance Method Details

#memoize(method_name, ttl: nil, key: nil) ⇒ Object

Declare memoized methods with cache backing Example: memoize :method_name, ttl: 300, key: -> { “cache_key” }



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/fontist/memoizable.rb', line 33

def memoize(method_name, ttl: nil, key: nil)
  original_method = "_unmemoized_#{method_name}"
  alias_method original_method, method_name

  define_method(method_name) do |*args|
    cache_key = generate_memo_cache_key(method_name, args, key)

    # Try memory cache first (fastest)
    @memo_cache ||= {}
    @memo_cache_keys ||= Set.new

    if @memo_cache[cache_key]
      return @memo_cache[cache_key]
    end

    # Try disk cache (persistent across runs)
    cached = Fontist::Cache::Manager.get(cache_key)
    if cached && !memo_cache_expired?(cached)
      @memo_cache[cache_key] = cached
      @memo_cache_keys.add(cache_key)
      return cached
    end

    # Compute and cache
    result = send(original_method, *args)
    @memo_cache[cache_key] = result
    @memo_cache_keys.add(cache_key)
    Fontist::Cache::Manager.set(cache_key, result, ttl: ttl) if ttl

    result
  end
end