Class: Uchi::CallWithFlexibleArguments

Inherits:
Object
  • Object
show all
Defined in:
lib/uchi/call_with_flexible_arguments.rb

Overview

Provides a forward- and backwards compatible way of calling a proc.

Expects proc to accept only keyword arguments and calls the proc with only the keyword arguments it declares. Optional keyword arguments that are not provided are left out, so the proc's own default applies. A proc accepting **kwargs is called with all provided keyword arguments.

If the proc requires a keyword argument that is not provided an ArgumentError is raised.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(proc) ⇒ CallWithFlexibleArguments

Returns a new instance of CallWithFlexibleArguments.



45
46
47
# File 'lib/uchi/call_with_flexible_arguments.rb', line 45

def initialize(proc)
  @proc = proc
end

Instance Attribute Details

#proc ⇒ Object (readonly)

Returns the value of attribute proc.



14
15
16
# File 'lib/uchi/call_with_flexible_arguments.rb', line 14

def proc
  @proc
end

Instance Method Details

#call(**kwargs) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/uchi/call_with_flexible_arguments.rb', line 16

def call(**kwargs)
  parameters = proc.parameters

  positional = parameters.find { |type, _name| [:req, :opt].include?(type) }
  if positional
    raise \
      ArgumentError,
      "Expected #{proc.inspect} to accept only keyword arguments, but " \
      "it declares positional parameter: #{positional.last}"
  end

  return proc.call(**kwargs) if parameters.any? { |type, _name| type == :keyrest }

  # Generate a list of arguments both included in the proc's parameters and
  # present in the provided keyword arguments. Optional keyword arguments
  # not present in kwargs are omitted, so the proc's default applies.
  arguments = parameters.filter_map do |type, name|
    if kwargs.key?(name)
      [name, kwargs[name]]
    elsif type == :keyreq
      raise \
        ArgumentError,
        "Missing required keyword argument: #{name} in #{proc.inspect}"
    end
  end

  proc.call(**arguments.to_h)
end