18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# File 'lib/typed/coercion/struct_coercer.rb', line 18
def coerce(type:, value:)
return Failure.new(CoercionError.new("Field type must inherit from T::Struct for Struct coercion.")) unless used_for_type?(type)
return Success.new(value) if type.recursively_valid?(value)
return Failure.new(CoercionError.new("Value of type '#{value.class}' cannot be coerced to #{type} Struct.")) unless value.is_a?(Hash)
deserialization_result = T.cast(type, T::Types::Simple)
.raw_type
.deserialize_from(:hash, value)
if deserialization_result.success?
deserialization_result
else
Failure.new(CoercionError.new(deserialization_result.error.message))
end
rescue ArgumentError, RuntimeError
Failure.new(CoercionError.new("Given hash could not be coerced to #{type}."))
end
|