From 1d991c6192ff164f1ce8ed72936a50eef47d0bd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=94=A6=E5=BF=83?= <41134017+Lhcfl@users.noreply.github.com> Date: Wed, 21 Aug 2024 15:39:56 +0800 Subject: [PATCH] FIX: fix double validation (#314) 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 --- lib/discourse_data_explorer/parameter.rb | 6 +++--- spec/lib/parameter_spec.rb | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/discourse_data_explorer/parameter.rb b/lib/discourse_data_explorer/parameter.rb index a49de14..9619625 100644 --- a/lib/discourse_data_explorer/parameter.rb +++ b/lib/discourse_data_explorer/parameter.rb @@ -153,16 +153,16 @@ module ::DiscourseDataExplorer 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 eeea570..ea30003 100644 --- a/spec/lib/parameter_spec.rb +++ b/spec/lib/parameter_spec.rb @@ -16,6 +16,26 @@ RSpec.describe DiscourseDataExplorer::Parameter do ) 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)