Sha256: 92a3d4c6441ac19a5568e0848b7d509eacd394a1ebc61eda8fa8430dae690511

Contents?: true

Size: 1.88 KB

Versions: 7

Compression:

Stored size: 1.88 KB

Contents

module Dry
  module Types
    module Builder
      include Dry::Core::Constants

      # @return [Class]
      def constrained_type
        Constrained
      end

      # @param [Type] other
      # @return [Sum, Sum::Constrained]
      def |(other)
        klass = constrained? && other.constrained? ? Sum::Constrained : Sum
        klass.new(self, other)
      end

      # @return [Sum]
      def optional
        Types['strict.nil'] | self
      end

      # @param [Hash] options constraining rule (see {Types.Rule})
      # @return [Constrained]
      def constrained(options)
        constrained_type.new(self, rule: Types.Rule(options))
      end

      # @param [Object] input
      # @param [#call,nil] block
      # @raise [ConstraintError]
      # @return [Default]
      def default(input = Undefined, &block)
        value = input.equal?(Undefined) ? block : input

        if value.is_a?(Proc) || valid?(value)
          Default[value].new(self, value)
        else
          raise ConstraintError.new("default value #{value.inspect} violates constraints", value)
        end
      end

      # @param [Array] values
      # @return [Enum]
      def enum(*values)
        mapping =
          if values.length == 1 && values[0].is_a?(::Hash)
            values[0]
          else
            ::Hash[values.zip(values)]
          end

        Enum.new(constrained(included_in: mapping.keys), mapping: mapping)
      end

      # @return [Safe]
      def safe
        Safe.new(self)
      end

      # @param [#call,nil] constructor
      # @param [Hash] options
      # @param [#call,nil] block
      # @return [Constructor]
      def constructor(constructor = nil, **options, &block)
        Constructor.new(with(options), fn: constructor || block)
      end
    end
  end
end

require 'dry/types/default'
require 'dry/types/constrained'
require 'dry/types/enum'
require 'dry/types/safe'
require 'dry/types/sum'

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
dry-types-0.14.1 lib/dry/types/builder.rb
dry-types-0.14.0 lib/dry/types/builder.rb
dry-types-0.13.4 lib/dry/types/builder.rb
dry-types-0.13.3 lib/dry/types/builder.rb
dry-types-0.13.2 lib/dry/types/builder.rb
dry-types-0.13.1 lib/dry/types/builder.rb
dry-types-0.13.0 lib/dry/types/builder.rb