Class: Defi::Value

Inherits:
Object
  • Object
show all
Defined in:
lib/defi/value.rb

Overview

Represents a result of an operation, encapsulating either the returned value or an exception raised during the execution.

This class is used to handle the outcome of a method invocation, allowing to distinguish between successful results and exceptions.

Constant Summary collapse

RAISE =
"raise"
RETURN =
"return"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeValue

Initializes a Value object with the result of the provided block. Captures any exception raised during the block execution.

rubocop:disable Lint/RescueException

Examples:

value = Defi::Value.new { 1 + 1 }
value.call # => 2

Handling an exception

value = Defi::Value.new { raise 'Error' }
value.call # raises 'Error'

Yield Returns:

  • (#object_id)

    The result of the block or the exception raised.



29
30
31
32
33
34
35
# File 'lib/defi/value.rb', line 29

def initialize
  @object = yield
  @raised = false
rescue ::Exception => e
  @object = e
  @raised = true
end

Instance Attribute Details

#object#object_id (readonly)

Returns The returned or the raised object.

Returns:

  • (#object_id)

    The returned or the raised object.



14
15
16
# File 'lib/defi/value.rb', line 14

def object
  @object
end

Instance Method Details

#call#object_id

Returns the object if no exception was raised, otherwise raises the exception.

Examples:

value = Defi::Value.new { "Hello" }
value.call # => "Hello"

Returns:

  • (#object_id)

    The returned object or raises the captured exception.



45
46
47
48
49
# File 'lib/defi/value.rb', line 45

def call
  raise object if raised?

  object
end

#inspectString

Returns a human-readable representation of the Value object.

Returns:

  • (String)

    The human-readable representation of the Value object.



82
83
84
# File 'lib/defi/value.rb', line 82

def inspect
  "Value(object: #{object}, raised: #{raised?})"
end

#raised?Boolean

Checks if an exception was raised during the execution.

Examples:

value = Defi::Value.new { raise 'Error' }
value.raised? # => true

Returns:

  • (Boolean)

    True if an exception was raised, otherwise false.



58
59
60
# File 'lib/defi/value.rb', line 58

def raised?
  @raised
end

#to_hHash

Returns a hash containing the properties of the Value object.

Returns:

  • (Hash)

    The properties of the Value object.



65
66
67
68
69
70
# File 'lib/defi/value.rb', line 65

def to_h
  {
    raised: raised?,
    object:
  }
end

#to_sString

Returns a string representation of the Value object.

Returns:

  • (String)

    The string representation of the Value object.



75
76
77
# File 'lib/defi/value.rb', line 75

def to_s
  "#{raise_or_return} #{object}"
end