Module: Philiprehberger::Try

Defined in:
lib/philiprehberger/try.rb,
lib/philiprehberger/try/version.rb

Defined Under Namespace

Classes: Failure, Success

Constant Summary collapse

VERSION =
'0.5.0'

Class Method Summary collapse

Class Method Details

.all(*items) ⇒ Success, Failure

Combine multiple Try results or callables into a single result.

Accepts any mix of Success, Failure, Proc, or lambda objects. Procs/lambdas are evaluated lazily via Try.call and short-circuit on the first failure.

Parameters:

Returns:

  • (Success, Failure)

    Success wrapping an array of values, or the first Failure



27
28
29
30
31
32
33
34
35
36
# File 'lib/philiprehberger/try.rb', line 27

def self.all(*items)
  values = []
  items.each do |item|
    result = item.is_a?(Proc) ? call(&item) : item
    return result if result.failure?

    values << result.value
  end
  Success.new(values)
end

.call(timeout: nil, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/philiprehberger/try.rb', line 8

def self.call(timeout: nil, &block)
  value = if timeout
            Timeout.timeout(timeout, &block)
          else
            yield
          end
  Success.new(value)
rescue StandardError => e
  Failure.new(e)
end