1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
# frozen_string_literal: true
module Dry
module Types
class Constrained
# Common coercion-related API for constrained types
#
# @api public
class Coercible < Constrained
# @return [Object]
#
# @api private
def call_unsafe(input)
coerced = type.call_unsafe(input)
result = rule.(coerced)
if result.success?
coerced
else
raise ConstraintError.new(result, input)
end
end
# @return [Object]
#
# @api private
def call_safe(input)
coerced = type.call_safe(input) { return yield }
if rule[coerced]
coerced
else
yield(coerced)
end
end
# @see Dry::Types::Constrained#try
#
# @api public
def try(input, &block)
result = type.try(input)
if result.success?
validation = rule.(result.input)
if validation.success?
result
else
failure = failure(result.input, ConstraintError.new(validation, input))
block ? yield(failure) : failure
end
else
block ? yield(result) : result
end
end
end
end
end
end
|