Module: ToResultMixin

Defined in:
lib/to-result.rb

Defined Under Namespace

Classes: Configuration

Constant Summary collapse

@@configuration =
Configuration.new

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configure {|@@configuration| ... } ⇒ Object

Allow to override the @@configuration fields

Yields:

  • (@@configuration)


21
22
23
# File 'lib/to-result.rb', line 21

def self.configure
  yield @@configuration
end

Instance Method Details

#ToResult(only: [StandardError], **args, &block) ⇒ Success, Failure

ToResult executes a block of code and returns Success or Failure. All exceptions inherited from StandardError are catched and converted to Failure or you can pass a custom list of exceptions to catch using ‘only`.

Passing the ‘on_error` block overrides the global on_error defined in to the Configuration, it is possible to pass `nil` to not execute a block when an error is catched.

Parameters:

  • only (Array<Class>) (defaults to: [StandardError])

    is the array of Exception to catch

  • on_error (Proc|Method)

    is the function to be executed in case of error. It overrides the global on_error.

  • &f (Proc)

    is the block to run

Returns:

  • (Success)
  • (Failure)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/to-result.rb', line 42

def ToResult(only: [StandardError], **args, &block)
  # on_error included in args so we can distinguish when it's passed but it's nil
  # from when it's not passed at all
  on_error ||= args.key?(:on_error) ? args[:on_error] : @@configuration.on_error

  block_wrapper =
    proc do
      block.call
    rescue Dry::Monads::Do::Halt => e
      failure = error = e.result
      error = error.failure if error.respond_to?(:failure)
      on_error.call(error) if on_error.respond_to?(:call)
      return failure
    rescue *only => e
      on_error.call(e) if on_error.respond_to?(:call)
      raise e
    end

  Try.run(only, block_wrapper).to_result
end