Sha256: 7a71f440985d65925828c11b39add642497db49594ccdd8af2727e10f659a120

Contents?: true

Size: 1.91 KB

Versions: 2

Compression:

Stored size: 1.91 KB

Contents

# 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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
litl-0.1.1 lib/lit/loader.rb
litl-0.1.0 lib/lit/loader.rb