Sha256: 95f8f54b1341e5f16d418a94646cdf49112045f3f481ee601d27fd5df0611ee2

Contents?: true

Size: 1.06 KB

Versions: 10

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

module Kind
  class Result::Success < Result::Monad
    DEFAULT_TYPE = :ok

    def success?
      true
    end

    def value_or(_default = UNDEFINED, &block)
      @value
    end

    def map(callable = UNDEFINED, &fn)
      _resolve_map(callable, fn)
    rescue Kind::Monad::Error => e
      raise e
    rescue StandardError => e
      Result::Failure[:exception, e]
    end

    alias_method :then, :map
    alias_method :and_then, :map

    def map!(callable = UNDEFINED, &fn)
      _resolve_map(callable, fn)
    end

    alias_method :|, :map!
    alias_method :>>, :map!
    alias_method :then!, :map!
    alias_method :and_then!, :map!

    def inspect
      '#<%s type=%p value=%p>' % ['Kind::Success', type, value]
    end

    private

      def _resolve_map(callable, fn)
        callable.respond_to?(:call) ? _map(callable) : _map(fn)
      end

      def _map(fn)
        monad = fn.call(@value)

        return monad if Result::Monad === monad

        raise Kind::Monad::Error.new('Kind::Success | Kind::Failure', monad)
      end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
kind-5.10.0 lib/kind/result/success.rb
kind-5.9.0 lib/kind/result/success.rb
kind-5.8.1 lib/kind/result/success.rb
kind-5.8.0 lib/kind/result/success.rb
kind-5.7.0 lib/kind/result/success.rb
kind-5.6.0 lib/kind/result/success.rb
kind-5.5.0 lib/kind/result/success.rb
kind-5.4.1 lib/kind/result/success.rb
kind-5.4.0 lib/kind/result/success.rb
kind-5.3.0 lib/kind/result/success.rb