Sha256: 8f3980550e351978aa73fcd32a19bd8d3912a270493eb33c0a06626510eee660

Contents?: true

Size: 1.08 KB

Versions: 1

Compression:

Stored size: 1.08 KB

Contents

require 'dry/types/options'

module Dry
  module Types
    class Sum
      include Dry::Equalizer(:left, :right, :options)
      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

1 entries across 1 versions & 1 rubygems

Version Path
dry-types-0.7.2 lib/dry/types/sum.rb