fix(conditional): only parse user input as int if compared with a number

This commit is contained in:
simon lehericey 2022-09-09 10:37:31 +02:00
parent 478a7e68ab
commit c43bf2e5c9
3 changed files with 25 additions and 7 deletions

View file

@ -39,20 +39,27 @@ class ConditionForm
def row_to_condition(row)
left = Logic.from_json(row[:targeted_champ])
right = parse_value(row[:value])
right = parse_value(left.type, row[:value])
Logic.class_from_name(row[:operator_name]).new(left, right)
end
def parse_value(value)
def parse_value(left_type, value)
return empty if value.blank?
number = Integer(value) rescue nil
return constant(number) if number.present?
if left_type == :number
# in this special case, we try to cast as Integer
# but it can still be a previous string value or a mistap
number = Integer(value) rescue nil
return constant(number) if number
end
json = JSON.parse(value) rescue nil
return Logic.from_json(value) if json.present?
# otherwise it can be a serialized Constant(true | false) term
# or a serialized Empty term
term = Logic.from_json(value) rescue nil
return term if term.present?
# if anything else, save it as a constant of string
constant(value)
end
end

View file

@ -32,7 +32,7 @@ describe Administrateurs::ConditionsController, type: :controller do
end
it do
expect(second_tdc.reload.condition).to eq(ds_eq(champ_value(1), constant(2)))
expect(second_tdc.reload.condition).to eq(ds_eq(champ_value(1), constant('2')))
expect(assigns(:coordinate)).to eq(procedure.draft_revision.coordinate_for(second_tdc))
expect(assigns(:upper_tdcs)).to eq([first_coordinate.type_de_champ])
end

View file

@ -3,12 +3,23 @@ describe ConditionForm, type: :model do
describe 'to_condition' do
let(:top_operator_name) { '' }
let(:champ_value_type) { :number }
subject { ConditionForm.new(rows: rows, top_operator_name: top_operator_name).to_condition }
before do
allow_any_instance_of(Logic::ChampValue).to receive(:type).and_return(champ_value_type)
end
context 'when a row is added' do
let(:rows) { [{ targeted_champ: champ_value(1).to_json, operator_name: Logic::Eq.name, value: '1' }] }
it { is_expected.to eq(ds_eq(champ_value(1), constant(1))) }
context 'with a targeted enum' do
let(:champ_value_type) { :enum }
it { is_expected.to eq(ds_eq(champ_value(1), constant('1'))) }
end
end
context 'when two rows are added' do