Class: Subroutine::TypeCaster

Inherits:
Object
  • Object
show all
Defined in:
lib/subroutine/type_caster.rb

Constant Summary collapse

TYPES =
{
  :integer => [:int, :integer, :epoch],
  :number => [:number, :float],
  :decimal => [:decimal, :big_decimal],
  :string => [:string, :text],
  :boolean => [:bool, :boolean],
  :iso_date => [:iso_date],
  :iso_time => [:iso_time],
  :date => [:date],
  :time => [:time, :timestamp],
  :hash => [:object, :hashmap, :dict],
  :array => [:array]
}

Instance Method Summary collapse

Instance Method Details

#cast(value, type) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/subroutine/type_caster.rb', line 27

def cast(value, type)
  return value if value.nil? || type.nil?

  case type.to_sym
  when *TYPES[:integer]
    cast_number(value).try(:to_i)
  when *TYPES[:number]
    cast_number(value).try(:to_f)
  when *TYPES[:decimal]
    d = cast_number(value)
    d ? BigDecimal(d.to_s) : nil
  when *TYPES[:string]
    cast_string(value)
  when *TYPES[:boolean]
    cast_boolean(value)
  when *TYPES[:iso_date]
    t = cast_iso_time(value)
    t ? t.split('T')[0] : t
  when *TYPES[:date]
    cast_date(value).try(:to_date)
  when *TYPES[:iso_time]
    cast_iso_time(value)
  when *TYPES[:time]
    cast_time(value)
  when *TYPES[:hash]
    cast_hash(value)
  when *TYPES[:array]
    cast_array(value)
  else
    value
  end
end