require 'fileutils' module UniverseCompiler module Persistence class BasicYamlEngine attr_accessor :universe, :universe_uri def initialize(universe, universe_uri) @universe = universe @universe_uri = universe_uri end def export_universe FileUtils.mkdir_p universe_uri universe.get_entities.each do |entity| export_entity entity end end def import_universe(recursive: false, stop_on_error: true, &block) sub_search_path = recursive ? '**' : '*' glob_pattern = File.join universe_uri, sub_search_path, '*.yaml' Dir.glob(glob_pattern) do |file| UniverseCompiler.logger.debug "Importing '#{file}' entity file." new_entity = nil begin new_entity = import_entity file rescue => e raise e if stop_on_error end if new_entity.nil? UniverseCompiler.logger.debug "#{e.message}\nBacktrace:\n#{e.backtrace.join("\n\t")}" UniverseCompiler.logger.warn "Could not load entity from file '#{file}' because '#{e.message}'" else block.call new_entity if block_given? end end end def export_entity(entity) dir = File.join(universe_uri, entity.type.to_s) FileUtils.mkdir_p dir entity_file = entity.source_uri || File.join(dir, "#{entity.name}.yaml") entity.save entity_file UniverseCompiler.logger.info 'Exporting entity "%s" to file "%s"' % [entity.name, entity_file] UniverseCompiler.logger.debug "Saved entity:\n%s" % [entity.to_yaml] end def import_entity(uri) entity = UniverseCompiler::Entity::Persistence.load uri universe.add entity # Fix references link to universe entity.traverse_fields do |leaf| if leaf.is_a? UniverseCompiler::Entity::Reference leaf.universe = universe end end entity end end end end