Class: Upgrow::Result

Inherits:
ImmutableStruct show all
Defined in:
lib/upgrow/result.rb

Overview

Results are special Structs that are generated dynamically to accommodate a set of pre-defined members. Since different Actions might want to return zero to multiple values, they are always returned as members of a Result instance.

Regardless of the values the Action might want to return, a Result has one default member called errors, which holds any errors that might occur when the Action is performed. If Result errors are empty, the Result is a success; if there are errors present, however, the Result is a failure. This empowers Actions with a predictable public interface, so callers can expect how to evaluate if an operation was successful or not by simply checking the success or failure of a Result.

Additionally, Result instances behave like monadic values by offering bindings to be called only in case of success or failure, which further simplifies the caller’s code by not having to use conditional to check for errors.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**values) ⇒ Result

Returns a new Result instance populated with the given values.

Parameters:

  • values (Hash<Symbol, Object>)

    the list of values for each member provided as keyword arguments.



43
44
45
46
# File 'lib/upgrow/result.rb', line 43

def initialize(**values)
  errors = values.fetch(:errors, [])
  super(**values.merge(errors: errors))
end

Class Method Details

.new(*members) ⇒ Result

Creates a new Result class that can handle the given members.

Parameters:

  • members (Array<Symbol>)

    the list of members the new Result should be able to hold.

Returns:

  • (Result)

    the new Result class with the given members.



31
32
33
34
# File 'lib/upgrow/result.rb', line 31

def new(*members)
  members << :errors unless members.include?(:errors)
  super(*members)
end

Instance Method Details

#success?true, false

Check if the Result is successful or not. A successful Result means there are no errors present.

Returns:

  • (true)

    if the Result is successful.

  • (false)

    if the Result is a failure.



53
54
55
# File 'lib/upgrow/result.rb', line 53

def success?
  errors.none?
end