diff --git a/lib/necromancer/converters/array.rb b/lib/necromancer/converters/array.rb index 75092dc..d5801fa 100644 --- a/lib/necromancer/converters/array.rb +++ b/lib/necromancer/converters/array.rb @@ -71,6 +71,17 @@ def call(array, strict: config.strict) end end + class ArrayToFloatArrayConverter < Converter + # @example + # converter.call(["1", "2", "3"]) # => [1.0, 2.0, 3.0] + # + # @api public + def call(array, strict: config.strict) + float_converter = NumericConverters::StringToFloatConverter.new(:string, :float) + array.map { |val| float_converter.(val, strict: strict) } + end + end + # An object that converts an array to an array with numeric values class ArrayToNumericConverter < Converter # Convert an array to an array of numeric values @@ -142,14 +153,20 @@ def call(value, strict: config.strict) def self.load(conversions) conversions.register NullConverter.new(:array, :array) + conversions.register StringToArrayConverter.new(:string, :array) conversions.register StringToBoolArrayConverter.new(:string, :bools) conversions.register StringToBoolArrayConverter.new(:string, :booleans) conversions.register StringToIntegerArrayConverter.new(:string, :integers) conversions.register StringToIntegerArrayConverter.new(:string, :ints) + conversions.register ArrayToNumericConverter.new(:array, :numeric) + conversions.register ArrayToIntegerArrayConverter.new(:array, :integers) + conversions.register ArrayToIntegerArrayConverter.new(:array, :ints) + conversions.register ArrayToFloatArrayConverter.new(:array, :floats) conversions.register ArrayToBooleanConverter.new(:array, :booleans) conversions.register ArrayToBooleanConverter.new(:array, :bools) + conversions.register ObjectToArrayConverter.new(:object, :array) conversions.register ObjectToArrayConverter.new(:hash, :array) end diff --git a/spec/unit/conversions/to_hash_spec.rb b/spec/unit/conversions/to_hash_spec.rb index e14721a..bd89c28 100644 --- a/spec/unit/conversions/to_hash_spec.rb +++ b/spec/unit/conversions/to_hash_spec.rb @@ -11,6 +11,9 @@ "array->array", "array->booleans", "array->bools", + "array->floats", + "array->integers", + "array->ints", "array->numeric", "boolean->boolean", "boolean->integer", diff --git a/spec/unit/converters/array_spec.rb b/spec/unit/converters/array_spec.rb index ce5dccc..fe5cf7c 100644 --- a/spec/unit/converters/array_spec.rb +++ b/spec/unit/converters/array_spec.rb @@ -102,6 +102,19 @@ end end + describe ":array -> :floats" do + subject(:converter) { described_class::ArrayToFloatArrayConverter.new } + + { + %w[1 2 3] => [1.0, 2.0, 3.0], + %w[1.2 2.3 3.4] => [1.2, 2.3, 3.4] + }.each do |input, obj| + it "converts #{input.inspect} to #{obj.inspect}" do + expect(converter.(input)).to eq(obj) + end + end + end + describe ":array -> :numeric" do subject(:converter) { described_class::ArrayToNumericConverter.new(:array, :numeric) }