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
|
# File 'lib/typed/coercion/typed_hash_coercer.rb', line 16
def coerce(type:, value:)
return Failure.new(CoercionError.new("Field type must be a T::Hash.")) unless used_for_type?(type)
return Failure.new(CoercionError.new("Value must be a Hash.")) unless value.is_a?(Hash)
return Success.new(value) if type.recursively_valid?(value)
coerced_hash = {}
errors = []
value.each do |k, v|
key_result = Coercion.coerce(type: T::Utils.coerce(T.cast(type, T::Types::TypedHash).type.types.first), value: k)
value_result = Coercion.coerce(type: T::Utils.coerce(T.cast(type, T::Types::TypedHash).type.types.last), value: v)
if key_result.success? && value_result.success?
coerced_hash[key_result.payload] = value_result.payload
else
if key_result.failure?
errors << key_result.error
end
if value_result.failure?
errors << value_result.error
end
end
end
if errors.empty?
Success.new(coerced_hash)
else
Failure.new(CoercionError.new(errors.map(&:message).join(" | ")))
end
end
|