diff --git a/lib/discourse_data_explorer/parameter.rb b/lib/discourse_data_explorer/parameter.rb index a49de144..96196253 100644 --- a/lib/discourse_data_explorer/parameter.rb +++ b/lib/discourse_data_explorer/parameter.rb @@ -153,16 +153,16 @@ def cast_to_ruby(string) invalid_format string, e.message end when :double - if string =~ /-?\d*(\.\d+)/ + if string.strip =~ /^-?\d*\.?\d+$/ value = Float(string) elsif string =~ /^(-?)Inf(inity)?$/i - if $1 + if $1.present? value = -Float::INFINITY else value = Float::INFINITY end elsif string =~ /^(-?)NaN$/i - if $1 + if $1.present? value = -Float::NAN else value = Float::NAN diff --git a/spec/lib/parameter_spec.rb b/spec/lib/parameter_spec.rb index eeea5702..ea300038 100644 --- a/spec/lib/parameter_spec.rb +++ b/spec/lib/parameter_spec.rb @@ -16,6 +16,26 @@ def param(identifier, type, default, nullable) ) end + describe "double type" do + let!(:double_param) { param("double", :double, nil, false) } + + it "raises an error if not a double" do + expect { double_param.cast_to_ruby("abcd") }.to raise_error( + ::DiscourseDataExplorer::ValidationError, + ) + end + + it "returns the float number if it can be a valid double" do + expect(double_param.cast_to_ruby("3.14")).to eq(3.14) + expect(double_param.cast_to_ruby(".314")).to eq(0.314) + expect(double_param.cast_to_ruby("1")).to eq(1.0) + expect(double_param.cast_to_ruby("Inf")).to eq(Float::INFINITY) + expect(double_param.cast_to_ruby("-Infinity")).to eq(-Float::INFINITY) + expect(double_param.cast_to_ruby("-NaN").nan?).to eq(true) + expect(double_param.cast_to_ruby("NaN").nan?).to eq(true) + end + end + describe "post_id type" do fab!(:post)