Module: SafeMemoize::PublicCustomKeyMethods

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

Overview

Instance-level custom cache key registration.

Instance Method Summary collapse

Instance Method Details

#clear_custom_keys(method_name = nil) ⇒ void

This method returns an undefined value.

Removes the custom key generator for one method, or all generators.

Parameters:

  • method_name (Symbol, String, nil) (defaults to: nil)

    when given, removes only that method's generator; when +nil+, removes all generators on this instance



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/safe_memoize/public_custom_key_methods.rb', line 34

def clear_custom_keys(method_name = nil)
  if method_name
    with_memo_lock do
      custom_key_store.delete(method_name.to_sym)
    end
  else
    with_memo_lock do
      _clear_custom_keys
    end
  end
end

#memoize_with_custom_key(method_name) {|*args, **kwargs| ... } ⇒ void

This method returns an undefined value.

Registers a per-instance custom key generator for a memoized method.

The block receives the same arguments as the method and should return a single value used as the cache key. Two calls that produce the same key value share one cached result, regardless of their raw arguments.

Instance-level keys take priority over the class-level +key:+ option set in ClassMethods#memoize.

Examples:

Collapse all option hashes that share the same user ID

obj.memoize_with_custom_key(:fetch) { |user_id, _options| user_id }

Parameters:

  • method_name (Symbol, String)

Yields:

  • (*args, **kwargs)

    called with the method's arguments on each invocation

Yield Returns:

  • (Object)

    the key value (must be comparable with +==+)

Raises:

  • (ArgumentError)

    if no block is given



23
24
25
26
27
# File 'lib/safe_memoize/public_custom_key_methods.rb', line 23

def memoize_with_custom_key(method_name, &key_generator)
  raise ArgumentError, "block required for key generation" unless key_generator

  register_custom_key(method_name, &key_generator)
end