Module: SmoothOperator::TypeConverter

Extended by:
TypeConverter
Included in:
TypeConverter
Defined in:
lib/smooth_operator/type_converter.rb

Instance Method Summary collapse

Instance Method Details

#cast_to_type(name, value, type, array_class, unknown_hash_class) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/smooth_operator/type_converter.rb', line 7

def cast_to_type(name, value, type, array_class, unknown_hash_class)
  case value
  when Array
    value.map { |array_entry| array_class.new(name, array_entry, type, unknown_hash_class).value }
  when Hash
    type.nil? ? new_unknown_hash(value, array_class, unknown_hash_class) : type.new(value)
  else
    TypeConverter.convert(value, type)
  end
end

#convert(value, type) ⇒ Object



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
# File 'lib/smooth_operator/type_converter.rb', line 18

def convert(value, type)
  case type

  when :string, :text, String
    value.to_s
  
  when :int, :integer, Integer, Fixnum
    to_int(value)

  when :date, Date
    to_date(value)

  when :float, Float
    to_float(value)

  when :bool, :boolean
    to_boolean(value)

  when :datetime, :date_time, DateTime
    to_datetime(value)

  else
    Helpers.duplicate(value)
  end
end

#to_boolean(string) ⇒ Object



62
63
64
65
66
# File 'lib/smooth_operator/type_converter.rb', line 62

def to_boolean(string)
  value = string.to_s.downcase

  ['1', 'true'].include?(value) ? true : ['0', 'false'].include?(value) ? false : nil
end

#to_date(string) ⇒ Object



50
51
52
53
54
# File 'lib/smooth_operator/type_converter.rb', line 50

def to_date(string)
  return string if string.is_a?(Date)

  Date.parse(string) rescue nil
end

#to_datetime(string) ⇒ Object



56
57
58
59
60
# File 'lib/smooth_operator/type_converter.rb', line 56

def to_datetime(string)
  return string if string.is_a?(DateTime)

  DateTime.parse(string) rescue nil
end

#to_float(string) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/smooth_operator/type_converter.rb', line 68

def to_float(string)
  return string if string.is_a?(Float)

  return 0 if string.nil? || !string.is_a?(String)
  
  value = string.scan(/-*\d+[,.]*\d*/).flatten.map(&:to_f).first

  value.nil? ? 0 : value
end

#to_int(string) ⇒ Object



44
45
46
47
48
# File 'lib/smooth_operator/type_converter.rb', line 44

def to_int(string)
  return string if string.is_a?(Fixnum)

  to_float(string).to_i
end