Module: Caoutsearch::Search::TypeCast
- Defined in:
- lib/caoutsearch/search/type_cast.rb
Constant Summary collapse
- BOOLEAN_FALSE_VALUES =
rubocop:disable Lint/BooleanSymbol
[ false, 0, "0", :"0", "f", :f, "F", :F, "false", :false, "FALSE", :FALSE, "off", :off, "OFF", :OFF ].to_set.freeze
Class Method Summary collapse
- .cast(type, value) ⇒ Object
-
.cast_as_boolean(value) ⇒ Object
rubocop:enable Lint/BooleanSymbol.
- .cast_as_date(value) ⇒ Object
- .cast_as_float(value) ⇒ Object
- .cast_as_geo_point(value) ⇒ Object
- .cast_as_integer(value) ⇒ Object
Class Method Details
.cast(type, value) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/caoutsearch/search/type_cast.rb', line 7 def cast(type, value) case type.to_s when "integer", "long", "short", "byte" cast_as_integer(value) when "double", "float", "half_float", "scaled_float" cast_as_float(value) when "boolean" cast_as_boolean(value) when "geo_point" cast_as_geo_point(value) when "date" cast_as_date(value) else value end end |
.cast_as_boolean(value) ⇒ Object
rubocop:enable Lint/BooleanSymbol
55 56 57 58 59 60 61 |
# File 'lib/caoutsearch/search/type_cast.rb', line 55 def cast_as_boolean(value) if value == "" nil else BOOLEAN_FALSE_VALUES.exclude?(value) end end |
.cast_as_date(value) ⇒ Object
74 75 76 77 78 79 80 |
# File 'lib/caoutsearch/search/type_cast.rb', line 74 def cast_as_date(value) return value if value.is_a?(String) && value.match?(/\Anow[+-]{0,1}\d*[yMwdhHms]{0,1}(\/d){0,1}\Z/) json_value = value.as_json if value.respond_to?(:as_json) json_value ||= MultiJson.dump(value) json_value if Time.parse(json_value) end |
.cast_as_float(value) ⇒ Object
33 34 35 36 37 38 39 40 |
# File 'lib/caoutsearch/search/type_cast.rb', line 33 def cast_as_float(value) case value when nil then nil when Array then value.map { |v| cast_as_float(v) } when String then value.to_s.delete(" ").tr(",", ".").to_f else value.to_f end end |
.cast_as_geo_point(value) ⇒ Object
63 64 65 66 67 68 69 70 71 72 |
# File 'lib/caoutsearch/search/type_cast.rb', line 63 def cast_as_geo_point(value) if value.is_a? Hash value = value.stringify_keys value = [value["lat"], value["lon"] || value["lng"]] end raise ArgumentError, "invalid geo point: #{value.inspect}" unless value.is_a?(Array) && value.length == 2 value.map(&:to_f).reverse end |
.cast_as_integer(value) ⇒ Object
24 25 26 27 28 29 30 31 |
# File 'lib/caoutsearch/search/type_cast.rb', line 24 def cast_as_integer(value) case value when nil then nil when Array then value.map { |v| cast_as_integer(v) } when String then value.delete(" ").to_i else value.to_i end end |