Sha256: 074a8d08d80a8251b746a9849a25c55f0d98c64feee76c7bb1a8aa41b5923add

Contents?: true

Size: 771 Bytes

Versions: 3

Compression:

Stored size: 771 Bytes

Contents

# frozen_string_literal: true

module Fear
  module TryApi
    # Constructs a +Try+ using the block. This
    # method ensures any non-fatal exception is caught and a
    # +Failure+ object is returned.
    # @return [Fear::Try]
    # @example
    #   Fear.try { 4/0 } #=> #<Fear::Failure exception=#<ZeroDivisionError: divided by 0>>
    #   Fear.try { 4/2 } #=> #<Fear::Success value=2>
    #
    def try
      success(yield)
    rescue StandardError => error
      failure(error)
    end

    # @param exception [StandardError]
    # @return [Fear::Failure]
    #
    def failure(exception)
      Fear::Failure.new(exception)
    end

    # @param value [any]
    # @return [Fear::Success]
    #
    def success(value)
      Fear::Success.new(value)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
fear-3.0.0 lib/fear/try_api.rb
fear-1.2.0 lib/fear/try_api.rb
fear-1.1.0 lib/fear/try_api.rb