Skip to content

Commit

Permalink
Add string to array of floats conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Jul 13, 2020
1 parent 47bea47 commit f67730c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/necromancer/converters/array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ def call(string, strict: config.strict)
end
end

class StringToFloatArrayConverter < Converter
# @example
# converter.call("1,2,3") # => [1.0, 2.0, 3.0]
#
# @api public
def call(string, strict: config.strict)
array_converter = StringToArrayConverter.new(:string, :array)
array = array_converter.(string, strict: strict)
float_converter = ArrayToFloatArrayConverter.new(:array, :floats)
float_converter.(array, strict: strict)
end
end

class ArrayToIntegerArrayConverter < Converter
# @example
# converter.call(["1", "2", "3"]) # => [1, 2, 3]
Expand Down Expand Up @@ -159,6 +172,7 @@ def self.load(conversions)
conversions.register StringToBoolArrayConverter.new(:string, :booleans)
conversions.register StringToIntegerArrayConverter.new(:string, :integers)
conversions.register StringToIntegerArrayConverter.new(:string, :ints)
conversions.register StringToFloatArrayConverter.new(:string, :floats)

conversions.register ArrayToNumericConverter.new(:array, :numeric)
conversions.register ArrayToIntegerArrayConverter.new(:array, :integers)
Expand Down
1 change: 1 addition & 0 deletions spec/unit/conversions/to_hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"string->date",
"string->datetime",
"string->float",
"string->floats",
"string->hash",
"string->integer",
"string->integers",
Expand Down
20 changes: 20 additions & 0 deletions spec/unit/converters/array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,26 @@
end
end

describe ":string -> :floats" do
subject(:converter) { described_class::StringToFloatArrayConverter.new }

{
"1,2,3" => [1.0, 2.0, 3.0],
"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

it "fails to convert in strict mode" do
expect {
converter.("1,unknown", strict: true)
}.to raise_error(Necromancer::ConversionTypeError,
"'unknown' could not be converted from `string` into `float`")
end
end

describe ":array -> :booleans" do
subject(:converter) { described_class::ArrayToBooleanConverter.new(:array, :boolean) }

Expand Down

0 comments on commit f67730c

Please sign in to comment.