Module: SafeMemoize::ClassMethods

Defined in:
lib/safe_memoize.rb

Instance Method Summary collapse

Instance Method Details

#memoize(method_name) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/safe_memoize.rb', line 13

def memoize(method_name)
  method_name = method_name.to_sym
  visibility = memoized_method_visibility(method_name)

  mod = Module.new do
    define_method(method_name) do |*args, **kwargs, &block|
      # Blocks bypass cache entirely — they aren't comparable
      return super(*args, **kwargs, &block) if block

      cache_key = safe_memo_cache_key(method_name, args, kwargs)

      # Fast path: check without lock
      return memo_cache_read(cache_key) if memo_cache_hit?(cache_key)

      memo_fetch_or_store(cache_key) { super(*args, **kwargs) }
    end

    send(visibility, method_name)
  end

  prepend mod
end