Module: SafeMemoize::FiberLocalMethods

Included in:
InstanceMethods
Defined in:
lib/safe_memoize/fiber_local_methods.rb

Overview

Public and private helpers for fiber-local memoization.

When a method is memoized with +fiber_local: true+, its cached values are stored in +Fiber[:safe_memoize]+ rather than instance variables, giving each fiber an isolated cache that is automatically discarded when the fiber terminates. No mutex is required because fibers are cooperative: only one fiber runs at a time within a thread.

Constant Summary collapse

FIBER_STORE_KEY =
:__safe_memoize__

Instance Method Summary collapse

Instance Method Details

#fiber_local_memoized?(method_name, *args, **kwargs, &block) ⇒ Boolean

Note:

In Ruby, +Fiber.new+ inherits the parent fiber's local storage. SafeMemoize detects inherited stores via an +:owner+ sentinel and creates a fresh isolated store for each fiber on first write.

Returns +true+ if the given call is currently cached in the current fiber.

Parameters:

  • method_name (Symbol, String)
  • args (Array)
  • kwargs (Hash)

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
# File 'lib/safe_memoize/fiber_local_methods.rb', line 24

def fiber_local_memoized?(method_name, *args, **kwargs, &block)
  return false if block

  method_name = method_name.to_sym
  cache_key = compute_cache_key(method_name, args, kwargs)
  record = fiber_memo_cache_or_nil&.[](cache_key)
  memo_record_live?(record)
end

#reset_all_fiber_memosvoid

This method returns an undefined value.

Clears all fiber-local cached entries for this instance in the current fiber.



57
58
59
60
61
62
# File 'lib/safe_memoize/fiber_local_methods.rb', line 57

def reset_all_fiber_memos
  store = Fiber[FIBER_STORE_KEY]
  return unless store&.[](:__owner__) == Fiber.current.object_id

  store.delete(object_id)
end

#reset_fiber_memo(method_name, *args, **kwargs) ⇒ void

This method returns an undefined value.

Removes one or all fiber-local cached entries for a method in the current fiber.

Parameters:

  • method_name (Symbol, String)
  • args (Array)
  • kwargs (Hash)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/safe_memoize/fiber_local_methods.rb', line 39

def reset_fiber_memo(method_name, *args, **kwargs)
  method_name = method_name.to_sym
  cache = fiber_memo_cache_or_nil
  return unless cache

  if args.empty? && kwargs.empty?
    cache.delete_if { |key, _| key[0] == method_name }
    fiber_memo_lru_or_nil&.delete(method_name)
  else
    cache_key = compute_cache_key(method_name, args, kwargs)
    cache.delete(cache_key)
    fiber_memo_lru_or_nil&.[](method_name)&.delete(cache_key)
  end
end