Module: ModelAttribute::Casts

Defined in:
lib/model_attribute/casts.rb

Class Method Summary collapse

Class Method Details

.cast(value, type) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
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
# File 'lib/model_attribute/casts.rb', line 4

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

  case type
  when :integer
    int = Integer(value)
    float = Float(value)
    raise ArgumentError, "Can't cast #{value.inspect} to an integer without loss of precision" unless int == float
    int
  when :boolean
    if !!value == value
      value
    elsif value == 't'
      true
    elsif value == 'f'
      false
    else
      raise ArgumentError, "Can't cast #{value.inspect} to boolean"
    end
  when :time
    case value
    when Time
      value
    when Date, DateTime
      value.to_time
    when Integer
      # Assume milliseconds since epoch.
      Time.at(value / 1000.0)
    when Numeric
      # Numeric, but not an integer. Assume seconds since epoch.
      Time.at(value)
    else
      Time.parse(value)
    end
  when :string
    String(value)
  when :json
    if valid_json?(value)
      value
    else
      raise ArgumentError, "JSON only supports nil, numeric, string, boolean and arrays and hashes of those."
    end
  else
    raise UnsupportedTypeError.new(type)
  end
end