# frozen_string_literal: true module LIT # @api public # @since 0.1.0 class Loader FILE_EXTENSION = ".lit" def initialize loader = self @target_module = Module.new do include ::LIT::Object define_singleton_method(:reload_file) do |file_path| loader.reload_file(file_path) end define_singleton_method(:serialize) do |object| Serializer.new(object).serialize end define_singleton_method(:deserialize_request) do |data| RequestDeserializer.new(data, self).deserialize_request end end @working_module = @target_module end def load_directory(dir_path) glob = File.join("**", "*#{FILE_EXTENSION}") @base_dir = Pathname.new(dir_path) Dir.glob(glob, base: dir_path) do |filename| load_file(filename) end @target_module end def reload_file(file_path) @working_module = @target_module load_file(file_path) end private def load_file(filename) file_path = Pathname.new(File.expand_path(filename, @base_dir)) relative_path = file_path.relative_path_from(@base_dir).to_s namespace = [*File.dirname(relative_path).split(File::SEPARATOR).slice(1), File.basename(relative_path, FILE_EXTENSION)] if namespace == %w[main] load_main_file(file_path) else load_regular_file(file_path, namespace) end end def load_main_file(file_path) ast = Parser.parse_file(file_path) Builder::Object.new(ast, @target_module).build end def load_regular_file(file_path, namespace) namespace.each do |mod| @working_module = Utils.const_reset(@working_module, Utils.camelize(mod), Module.new) end ast = Parser.parse_file(file_path) Builder::Object.new(ast, @working_module).build @working_module.include(@target_module) end end end