module UniverseCompiler module Entity module Validation def invalid_fields invalid = {} self.class.fields_constraints.each do |field_name, constraints| constraints.each do |constraint_name, value| case constraint_name when :not_null invalid_for_constraint invalid, field_name, constraint_name, value if fields[field_name].nil? when :not_empty invalid_for_constraint invalid, field_name, constraint_name, value if fields[field_name].nil? or fields[field_name].empty? when :should_match unless fields[field_name].nil? invalid_for_constraint invalid, field_name, constraint_name, value unless fields[field_name].to_s.match value end when :class_name unless fields[field_name].nil? case value when String invalid_for_constraint invalid, field_name, constraint_name, value unless fields[field_name].class.name == value else invalid_for_constraint invalid, field_name, constraint_name, value unless fields[field_name].class == value end end when :is_array if fields[field_name].nil? or not fields[field_name].is_a? Array invalid_for_constraint invalid, field_name, constraint_name, value end when :is_hash if fields[field_name].nil? or not fields[field_name].is_a? Hash invalid_for_constraint invalid, field_name, constraint_name, value end when :has_one unless fields[field_name].nil? if fields[field_name].respond_to? :type invalid_for_constraint invalid, field_name, constraint_name, value unless fields[field_name].type == value else invalid_for_constraint invalid, field_name, constraint_name, value end end when :has_many if fields[field_name].nil? or not fields[field_name].is_a? Array invalid_for_constraint invalid, field_name, constraint_name, value else fields[field_name].each do |related_object| if related_object.respond_to? :type invalid_for_constraint invalid, field_name, constraint_name, value unless related_object.type == value else invalid_for_constraint invalid, field_name, constraint_name, value end end end else UniverseCompiler.logger.warn "Cannot handle unknown constraint '#{constraint_name}'! Skipping..." end end end invalid end def valid_for_fields_constraints?(raise_error: false) return true if invalid_fields.empty? invalid_fields.each do |name,value| UniverseCompiler.logger.error "Invalid field '#{name}' not compliant with '#{value}'" end fields_labels = invalid_fields.keys.join ', ' false_or_raise "Invalid entity '#{to_composite_key}' for fields #{fields_labels} !", raise_error: raise_error end def valid?(raise_error: false) return false unless valid_for_fields_constraints? raise_error: raise_error return false unless valid_for_inheritance? raise_error: raise_error if respond_to? :specifically_valid? return false unless specifically_valid? raise_error: raise_error end true end private def invalid_for_constraint(invalid_fields_definition, field_name, constraint_name, value) invalid_fields_definition[field_name] ||= [] invalid_fields_definition[field_name] << { constraint_name => value} end end end end