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
|
# File 'lib/attributed_object_helpers/type_coerce.rb', line 16
def self.coerce(type_info, value, coerce_blanks_to_nil: false)
return nil if value.nil?
return nil if coerce_blanks_to_nil && !(type_info == :string && value == '')
case type_info
when :string
return value.to_s
when :boolean
return [true, 1, 'true', '1'].include?(value)
when :integer
return value.to_i
when :float
return value.to_f
when :numeric
return (float = value.to_f) && (float % 1.0 == 0) ? float.to_i : float
when :symbol
return value.to_sym
else
if type_info.is_a?(Class) && type_info.respond_to?(:attributed_object)
return value if value.is_a?(type_info)
if !value.is_a?(Hash)
raise AttributedObject::UncoercibleValueError.new("Trying to coerce into #{type_info}, but value is not a hash, its #{value.class}")
end
return type_info.new(value)
end
if type_info.is_a?(Class)
return value if value.is_a?(type_info)
raise AttributedObject::UncoercibleValueError.new("Trying to coerce into #{type_info}, but no coercion is registered for #{type_info}->#{value.class}")
end
if type_info.is_a?(AttributedObject::Type)
return type_info.coerce(value)
end
raise AttributedObject::ConfigurationError.new("Unknown Type for type coerce #{type_info}")
end
end
|