Sha256: dbb4e3ec53bb2d7ee2d1e04e0c08331fead24cd51c2be913f046726c55d66842

Contents?: true

Size: 964 Bytes

Versions: 3

Compression:

Stored size: 964 Bytes

Contents

require 'dry/types/decorator'
require 'dry/types/constraints'
require 'dry/types/constrained/coercible'

module Dry
  module Types
    class Constrained
      include Decorator
      include Builder

      attr_reader :rule

      def initialize(type, options)
        super
        @rule = options.fetch(:rule)
      end

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

      def try(input, &block)
        validation = rule.(input)

        if validation.success?
          type.try(input, &block)
        else
          block ? yield(validation) : validation
        end
      end

      def valid?(value)
        rule.(value).success?
      end

      def constrained(options)
        with(rule: rule & Types.Rule(options))
      end

      private

      def decorate?(response)
        super || response.kind_of?(Constructor)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
dry-types-0.7.2 lib/dry/types/constrained.rb
dry-types-0.7.1 lib/dry/types/constrained.rb
dry-types-0.7.0 lib/dry/types/constrained.rb