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

44 lines
1.1 KiB
Ruby
Raw Normal View History

2022-06-09 14:00:18 +02:00
class Logic::NAryOperator < Logic::Term
attr_reader :operands
def initialize(operands)
2022-06-09 14:00:18 +02:00
@operands = operands
end
def to_h
{
2022-07-05 14:47:32 +02:00
"term" => self.class.name,
"operands" => @operands.map(&:to_h)
2022-06-09 14:00:18 +02:00
}
end
def self.from_h(h)
self.new(h['operands'].map { |operand_h| Logic.from_h(operand_h) })
2022-06-09 14:00:18 +02:00
end
2022-09-26 21:11:43 +02:00
def errors(type_de_champs = [])
2022-06-09 14:00:18 +02:00
errors = []
if @operands.empty?
errors += ["opérateur '#{operator_name}' vide"]
end
2022-09-26 21:07:43 +02:00
not_booleans = @operands.filter { |operand| operand.type(type_de_champs) != :boolean }
2022-06-09 14:00:18 +02:00
if not_booleans.present?
2022-09-26 21:21:55 +02:00
errors += ["'#{operator_name}' ne contient pas que des booléens : #{not_booleans.map { |o| o.to_s(type_de_champs) }.join(', ')}"]
2022-06-09 14:00:18 +02:00
end
2022-09-26 21:11:43 +02:00
errors + @operands.flat_map { |operand| operand.errors(type_de_champs) }
2022-06-09 14:00:18 +02:00
end
2022-09-26 21:07:43 +02:00
def type(_type_de_champs = []) = :boolean
2022-06-09 14:00:18 +02:00
def ==(other)
self.class == other.class &&
@operands.count == other.operands.count &&
@operands.all? do |operand|
@operands.count { |o| o == operand } == other.operands.count { |o| o == operand }
end
end
end