Module: CMDx::Utils::Call

Extended by:
Call
Included in:
Call
Defined in:
lib/cmdx/utils/call.rb

Overview

Utility module for invoking callable objects with different invocation strategies.

This module provides a unified interface for calling methods, procs, and other callable objects on target objects, handling the appropriate invocation method based on the callable type.

Instance Method Summary collapse

Instance Method Details

#invoke(target, callable, *args, **kwargs) {|Object| ... } ⇒ Object

Invokes a callable object on the target with the given arguments.

Examples:

Invoking a method by symbol

Call.invoke(user, :name)
Call.invoke(user, :update, { name: 'John' })

Invoking a proc

proc = ->(name) { "Hello #{name}" }
Call.invoke(user, proc, 'John')

Invoking a callable object

callable = MyCallable.new
Call.invoke(user, callable, 'data')

Parameters:

  • target (Object)

    The target object to invoke the callable on

  • callable (Symbol, Proc, #call)

    The callable to invoke

  • args (Array)

    Positional arguments to pass to the callable

  • kwargs (Hash)

    Keyword arguments to pass to the callable

Options Hash (**kwargs):

  • :* (Object)

    Any keyword arguments to pass to the callable

Yields:

  • (Object)

    Block to pass to the callable

Returns:

  • (Object)

    The result of invoking the callable

Raises:

  • (RuntimeError)

    When the callable cannot be invoked



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/cmdx/utils/call.rb', line 39

def invoke(target, callable, *args, **kwargs, &)
  if callable.is_a?(Symbol)
    target.send(callable, *args, **kwargs, &)
  elsif callable.is_a?(Proc)
    target.instance_exec(*args, **kwargs, &callable)
  elsif callable.respond_to?(:call)
    callable.call(*args, **kwargs, &)
  else
    raise "cannot invoke #{callable}"
  end
end