lib/universe_compiler/universe/entities.rb in universe_compiler-0.3.3 vs lib/universe_compiler/universe/entities.rb in universe_compiler-0.3.4
- old
+ new
@@ -31,10 +31,45 @@
add entity
self
end
def delete(entity)
+ # Remove references to entity
+ entities.each do |e|
+ e.class.fields_constraints.each do |field_name, constraints|
+ if constraints.keys.include? :has_one
+ e[field_name] = nil if e[field_name] == entity
+ end
+ if constraints.keys.include? :has_many
+ e[field_name].delete entity if e[field_name].include? entity
+ end
+ end
+ end
+ # Then delete the entity
entities.delete entity
+ reindex_all entities
+ end
+
+ def replace(entity, by)
+ raise UniverseCompiler::Error, "Wrong type, cannot replace '#{entity.as_path}' by '#{by.as_path}' !" unless entity.type == by.type
+ raise UniverseCompiler::Error, "Cannot replace '#{entity.as_path}' with '#{by.as_path}' which is alreadyin the universe!" if entity.universe == by.universe
+
+ # Change references to entity
+ entities.each do |e|
+ e.class.fields_constraints.each do |field_name, constraints|
+ if constraints.keys.include? :has_one
+ e[field_name] = by if e[field_name] == entity
+ end
+ if constraints.keys.include? :has_many
+ if e[field_name].map! do |entity_list_item|
+ (entity == entity_list_item) ? by : entity_list_item
+ end
+ end
+ end
+ end
+ end
+ # Then replace the entity
+ entities[entities.index(entity)] = by
reindex_all entities
end
def clear
entities.clear