Class: AttributedObjectHelpers::TypeCoerce

Inherits:
Object
  • Object
show all
Defined in:
lib/attributed_object_helpers/type_coerce.rb

Class Method Summary collapse

Class Method Details

.check_type_supported!(type_info) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/attributed_object_helpers/type_coerce.rb', line 3

def self.check_type_supported!(type_info)
  supported = type_info.is_a?(Class) || [
    :string,
    :boolean,
    :integer,
    :float,
    :numeric,
    :symbol
  ].include?(type_info)
  supported = type_info.is_a?(AttributedObject::Type) if !supported
  raise AttributedObject::ConfigurationError.new("Unknown Type for type coercion #{type_info}") unless supported
end

.coerce(type_info, value, coerce_blanks_to_nil: false) ⇒ Object



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 == '') # blank string stays blank

  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