29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/hashie/extensions/coercion.rb', line 29
def set_value_with_coercion(key, value)
into = self.class.key_coercion(key) || self.class.value_coercion(value)
return set_value_without_coercion(key, value) if value.nil? || into.nil?
begin
return set_value_without_coercion(key, coerce_or_init(into).call(value)) unless into.is_a?(Enumerable)
if into.class <= ::Hash
key_coerce = coerce_or_init(into.flatten[0])
value_coerce = coerce_or_init(into.flatten[-1])
value = into.class[value.map { |k, v| [key_coerce.call(k), value_coerce.call(v)] }]
else value_coerce = coerce_or_init(into.first)
value = into.class.new(value.map { |v| value_coerce.call(v) })
end
rescue NoMethodError, TypeError => e
raise CoercionError, "Cannot coerce property #{key.inspect} from #{value.class} to #{into}: #{e.message}"
end
set_value_without_coercion(key, value)
end
|