demarches-normaliennes/app/models/logic/binary_operator.rb

47 lines
1 KiB
Ruby
Raw Normal View History

2022-06-09 12:14:08 +02:00
class Logic::BinaryOperator < Logic::Term
attr_reader :left, :right
def initialize(left, right)
2022-06-09 12:14:08 +02:00
@left, @right = left, right
end
def to_h
{
2022-07-05 14:47:32 +02:00
"term" => self.class.name,
2022-06-09 12:14:08 +02:00
"left" => @left.to_h,
"right" => @right.to_h
2022-06-09 12:14:08 +02:00
}
end
def self.from_h(h)
self.new(Logic.from_h(h['left']), Logic.from_h(h['right']))
2022-06-09 12:14:08 +02:00
end
2022-09-26 21:11:43 +02:00
def errors(type_de_champs = [])
2022-06-09 12:14:08 +02:00
errors = []
2022-09-26 21:07:43 +02:00
if @left.type(type_de_champs) != :number || @right.type(type_de_champs) != :number
errors << { type: :required_number, operator_name: self.class.name }
2022-06-09 12:14:08 +02:00
end
2022-09-26 21:11:43 +02:00
errors + @left.errors(type_de_champs) + @right.errors(type_de_champs)
2022-06-09 12:14:08 +02:00
end
2022-09-26 21:07:43 +02:00
def type(type_de_champs = []) = :boolean
2022-06-09 12:14:08 +02:00
def compute(champs = [])
l = @left.compute(champs)
r = @right.compute(champs)
l&.send(operation, r) || false
2022-06-09 12:14:08 +02:00
end
2022-09-26 21:21:55 +02:00
def to_s(type_de_champs) = "(#{@left.to_s(type_de_champs)} #{operation} #{@right.to_s(type_de_champs)})"
2022-06-09 12:14:08 +02:00
def ==(other)
self.class == other.class &&
@left == other.left &&
@right == other.right
end
end