|
1 | 1 | # frozen_string_literal: true |
2 | 2 |
|
| 3 | +require "active_model" |
| 4 | + |
3 | 5 | module JsonPathAttribute |
4 | 6 | # Provides a way to cast values to a specific type |
5 | 7 | # This class is intended to be used internally by JsonPathAttribute |
6 | 8 | class Type |
7 | 9 | class << self |
8 | 10 | def cast_attribute(type, value, array: false) |
9 | 11 | return value if type == :source |
| 12 | + return cast_object_attribute(type, value, array: array) if type.is_a?(Class) |
10 | 13 |
|
11 | | - if value.nil? |
12 | | - return [] if array |
13 | | - return false if type == :boolean |
14 | | - end |
15 | | - |
16 | | - array ? cast_array(type, value) : cast_value(type, value, array) |
| 14 | + cast_to(type, value, array: array) |
17 | 15 | end |
18 | 16 |
|
19 | | - def cast_value(type, value, array) |
20 | | - return cast_object_attribute(type, value, array: array) if type.is_a?(Class) |
21 | | - return false if type == :boolean && value.nil? |
| 17 | + def cast_to(type, value, array: false) |
| 18 | + return [] if value.nil? && array |
| 19 | + return false if value.nil? && type == :boolean |
| 20 | + |
| 21 | + cast_type = ActiveModel::Type.lookup(type) |
22 | 22 |
|
23 | | - case type |
24 | | - when :string, :decimal |
25 | | - value.to_s |
26 | | - when :integer |
27 | | - value.to_i |
| 23 | + if array |
| 24 | + cast_array(value, type, cast_type) |
28 | 25 | else |
29 | | - raise TypeError, "Unable to cast #{value.inspect} to #{type}" |
| 26 | + cast_value(value, type, cast_type) |
| 27 | + end |
| 28 | + end |
| 29 | + |
| 30 | + def cast_array(values, type, cast_type) |
| 31 | + values.map do |value| |
| 32 | + next false if value.nil? && type == :boolean |
| 33 | + |
| 34 | + cast_type.cast(value) |
30 | 35 | end |
31 | 36 | end |
32 | 37 |
|
33 | | - def cast_array(type, values) |
34 | | - values.map { |element| cast_value(type, element, false) } |
| 38 | + def cast_value(value, type, cast_type) |
| 39 | + value = value.to_s if type == :decimal && value.is_a?(Float) |
| 40 | + |
| 41 | + cast_type.cast(value) |
35 | 42 | end |
36 | 43 |
|
37 | 44 | def cast_object_attribute(type, value, array:) |
|
0 commit comments