Sha256: 879aa1ae71a184340eed87d3d8e06c828a614bc3fd81c08a61e802855b788292

Contents?: true

Size: 1.97 KB

Versions: 2

Compression:

Stored size: 1.97 KB

Contents

require 'dry/types/options'

module Dry
  module Types
    class Sum
      include Dry::Equalizer(:left, :right, :options)
      include Builder
      include Options

      # @return [Definition]
      attr_reader :left

      # @return [Definition]
      attr_reader :right

      class Constrained < Sum
        # @return [Dry::Logic::Rule]
        def rule
          left.rule | right.rule
        end

        # @return [true]
        def constrained?
          true
        end

        # @param [Object] input
        # @return [Object]
        # @raise [ConstraintError] if given +input+ not passing {#try}
        def call(input)
          try(input) do |result|
            raise ConstraintError.new(result, input)
          end.input
        end
        alias_method :[], :call
      end

      # @param [Definition] left
      # @param [Definition] right
      # @param [Hash] options
      def initialize(left, right, options = {})
        super
        @left, @right = left, right
        freeze
      end

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

      # @return [false]
      def default?
        false
      end

      # @return [false]
      def maybe?
        false
      end

      # @return [false]
      def constrained?
        false
      end

      # @param [Object] input
      # @return [Object]
      def call(input)
        try(input).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

      # @param [Object] value
      # @return [Boolean]
      def primitive?(value)
        left.primitive?(value) || right.primitive?(value)
      end

      # @param [Object] value
      # @return [Boolean]
      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.9.4 lib/dry/types/sum.rb
dry-types-0.9.3 lib/dry/types/sum.rb