Skip to content

Commit

Permalink
FIX: fix double validation (#314)
Browse files Browse the repository at this point in the history
The old float validation had several bugs. It will recognize strings
like "a1.2" and "3.4b" as valid doubles, but will not recognize integers
like "1234" as doubles. Also, since an empty string is not falsy in Ruby,
it will recognize "Inf" as -Infinity.

This commit fixes these issues
  • Loading branch information
Lhcfl authored Aug 21, 2024
1 parent 6bf3ac7 commit 1d991c6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/discourse_data_explorer/parameter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions spec/lib/parameter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 1d991c6

Please sign in to comment.