Module: Callable::ClassMethods

Defined in:
lib/callable/mixin.rb

Instance Method Summary collapse

Instance Method Details

#call(*args, **kwargs) {|optional| ... } ⇒ Object

Instantiate the class and immediately invoke its instance ‘#call`.

Parameters:

  • args (Array)

    positional arguments for ‘initialize`.

  • kwargs (Hash)

    keyword arguments for ‘initialize`.

Yields:

  • (optional)

    block passed directly to the instance method ‘#call`; ignored if not yielded.

Returns:

  • anything returned by the instance ‘#call`.

Raises:

  • (ConstructionError)

    if construction fails (plain ‘ArgumentError`).

  • (NotImplementedError)

    if the instance does not implement ‘#call`.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/callable/mixin.rb', line 42

def call(*args, **kwargs, &block)
  # Ruby versions earlier than 2.7 can't reliably handle splatting empty kwargs, so branch for compatibility
  inst = kwargs.empty? ? new(*args) : new(*args, **kwargs)
rescue ArgumentError => e
  # Bubble up anything that isn't exactly ArgumentError (e.g., subclasses)
  raise unless e.instance_of?(ArgumentError)
  raise ConstructionError, "Cannot instantiate #{name}: #{e.message}", e.backtrace
else
  # Ensure the instance defines `#call`
  unless inst.respond_to?(:call)
    raise NotImplementedError, "#{name} must implement #call"
  end
  inst.call(&block)
end

#to_procProc

Returns a proc that delegates to ‘.call`, enabling `&MyService` shorthand.

Returns:

  • (Proc)

    a proc that delegates to ‘.call`, enabling `&MyService` shorthand.



58
59
60
# File 'lib/callable/mixin.rb', line 58

def to_proc
  method(:call).to_proc
end