Class: Defi::Method

Inherits:
BasicObject
Defined in:
lib/defi/method.rb

Overview

Represents a method to be applied against an object. Encapsulates method name, arguments, keyword arguments and blocks for dynamic method invocation with proper error handling.

Instance Method Summary collapse

Constructor Details

#initialize(name, *args, **opts, &block) ⇒ Method

Initialize a new Method object.

Parameters:

  • name (Symbol)

    The method name

  • args (Array)

    Positional arguments

  • opts (Hash)

    Keyword arguments

  • block (Proc)

    Optional block

Raises:

  • (ArgumentError)

    If name is not a Symbol, raises with the actual class received



16
17
18
19
20
21
22
23
# File 'lib/defi/method.rb', line 16

def initialize(name, *args, **opts, &block)
  raise ::ArgumentError, "Method name must be a Symbol, got: #{name.class}" unless name.is_a?(::Symbol)

  @name = name
  @args = args
  @opts = opts
  @block = block
end

Instance Method Details

#inspectString

Returns Human-readable representation.

Examples:

Defi::Method.new(:+, 1).inspect
# => "Defi(name: :+, args: [1], opts: {}, block: nil)"

Returns:

  • (String)

    Human-readable representation



58
59
60
61
62
63
64
# File 'lib/defi/method.rb', line 58

def inspect
  "Defi(" \
    "name: #{@name.inspect}, " \
    "args: #{@args.inspect}, " \
    "opts: #{@opts.inspect}, " \
    "block: #{@block.nil? ? "nil" : "<Proc>"})"
end

#to(object) ⇒ Defi::Value

Applies the method to the given object.

Examples:

Basic arithmetic

Defi::Method.new(:+, 1).to(2).call # => 3

Block usage

Defi::Method.new(:map) { |x| x * 2 }.to([1, 2, 3]).call # => [2, 4, 6]

Error handling

result = Defi::Method.new(:undefined).to(42)
result.raised? # => true

Parameters:

  • object (#object_id)

    Target object for method invocation

Returns:

  • (Defi::Value)

    Result wrapper containing return value or exception



39
40
41
# File 'lib/defi/method.rb', line 39

def to(object)
  Value.new { object.public_send(@name, *@args, **@opts, &@block) }
end

#to_hHash

Returns Method properties.

Returns:

  • (Hash)

    Method properties



44
45
46
47
48
49
50
51
# File 'lib/defi/method.rb', line 44

def to_h
  {
    name:  @name,
    args:  @args,
    opts:  @opts,
    block: @block
  }
end

#to_sString

Returns String representation of the method call.

Examples:

Defi::Method.new(:+, 1).to_s # => ".+(1)"
Defi::Method.new(:map) { |x| x }.to_s # => ".map(<Proc>)"

Returns:

  • (String)

    String representation of the method call



71
72
73
74
75
# File 'lib/defi/method.rb', line 71

def to_s
  return ".#{@name}" if no_arguments?

  ".#{@name}(#{stringified_arguments})"
end