2024-04-29 00:17:15 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2022-06-09 15:25:49 +02:00
|
|
|
class ConditionForm
|
|
|
|
include ActiveModel::Model
|
|
|
|
include Logic
|
|
|
|
|
2023-10-13 11:30:53 +02:00
|
|
|
attr_accessor :top_operator_name, :rows, :source_tdcs
|
2022-06-09 15:25:49 +02:00
|
|
|
|
|
|
|
def to_condition
|
|
|
|
case sub_conditions.count
|
|
|
|
when 0
|
|
|
|
nil
|
|
|
|
when 1
|
|
|
|
sub_conditions.first
|
|
|
|
else
|
|
|
|
top_operator_class.new(sub_conditions)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete_row(i)
|
|
|
|
rows.slice!(i)
|
|
|
|
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def change_champ(i)
|
2023-10-13 11:30:53 +02:00
|
|
|
sub_conditions[i] = Logic.ensure_compatibility_from_left(sub_conditions[i], source_tdcs)
|
2022-06-09 15:25:49 +02:00
|
|
|
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def top_operator_class
|
|
|
|
Logic.class_from_name(top_operator_name)
|
|
|
|
end
|
|
|
|
|
|
|
|
def sub_conditions
|
|
|
|
@sub_conditions ||= rows.map { |row| row_to_condition(row) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def row_to_condition(row)
|
|
|
|
left = Logic.from_json(row[:targeted_champ])
|
2023-10-13 11:30:53 +02:00
|
|
|
right = parse_value(left.type(source_tdcs), row[:value])
|
2022-06-09 15:25:49 +02:00
|
|
|
|
|
|
|
Logic.class_from_name(row[:operator_name]).new(left, right)
|
|
|
|
end
|
|
|
|
|
2022-09-09 10:37:31 +02:00
|
|
|
def parse_value(left_type, value)
|
2022-06-09 15:25:49 +02:00
|
|
|
return empty if value.blank?
|
|
|
|
|
2022-09-09 10:37:31 +02:00
|
|
|
if left_type == :number
|
2023-11-08 12:07:21 +01:00
|
|
|
# in this special case, we try to cast as Float, then Integer
|
2022-09-09 10:37:31 +02:00
|
|
|
# but it can still be a previous string value or a mistap
|
2023-11-08 12:07:21 +01:00
|
|
|
number = parse_to_number(value)
|
|
|
|
|
2022-09-09 10:37:31 +02:00
|
|
|
return constant(number) if number
|
|
|
|
end
|
2022-06-09 15:25:49 +02:00
|
|
|
|
2022-09-09 10:37:31 +02:00
|
|
|
# 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?
|
2022-06-09 15:25:49 +02:00
|
|
|
|
2022-09-09 10:37:31 +02:00
|
|
|
# if anything else, save it as a constant of string
|
2022-06-09 15:25:49 +02:00
|
|
|
constant(value)
|
|
|
|
end
|
2023-11-08 12:07:21 +01:00
|
|
|
|
|
|
|
def parse_to_number(str)
|
|
|
|
float = Float(str)
|
|
|
|
float % 1 == 0 ? float.to_i : float
|
|
|
|
rescue ArgumentError
|
|
|
|
nil
|
|
|
|
end
|
2022-06-09 15:25:49 +02:00
|
|
|
end
|