Sha256: 66c185216a20dd6ccc2f1cbf8d95e4bdebddd36affbfc20d7915bc067e1968f0

Contents?: true

Size: 1.03 KB

Versions: 2

Compression:

Stored size: 1.03 KB

Contents

require 'dry/types/options'

module Dry
  module Types
    class Sum
      include Builder
      include Options

      attr_reader :left

      attr_reader :right

      class Constrained < Sum
        def rule
          left.rule | right.rule
        end
      end

      def initialize(left, right, options = {})
        super
        @left, @right = left, right
        freeze
      end

      def name
        [left, right].map(&:name).join(' | ')
      end

      def call(input)
        try(input) do |result|
          raise ConstraintError, result
        end.input
      end
      alias_method :[], :call

      def try(input, &block)
        result = left.try(input) do
          right.try(input)
        end

        return result if result.success?

        if block
          yield(result)
        else
          result
        end
      end

      def primitive?(value)
        left.primitive?(value) || right.primitive?(value)
      end

      def valid?(value)
        left.valid?(value) || right.valid?(value)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-types-0.7.1 lib/dry/types/sum.rb
dry-types-0.7.0 lib/dry/types/sum.rb