lib/importmap/map.rb in importmap-rails-0.3.4 vs lib/importmap/map.rb in importmap-rails-0.4.0

- old
+ new

@@ -1,40 +1,53 @@ +require "pathname" + class Importmap::Map - attr_reader :files, :directories + attr_reader :packages, :directories attr_accessor :cached def initialize - @files, @directories = {}, {} + @packages, @directories = {}, {} end - def draw(&block) - instance_eval(&block) + def draw(path = nil, &block) + if path + begin + instance_eval(File.read(path)) + rescue Exception => e + Rails.logger.error "Unable to parse import map from #{path}: #{e.message}" + raise "Unable to parse import map from #{path}: #{e.message}" + end + else + instance_eval(&block) + end + + self end def pin(name, to: nil, preload: true) - @files[name] = MappedFile.new(name: name, path: to || "#{name}.js", preload: preload) + @packages[name] = MappedFile.new(name: name, path: to || "#{name}.js", preload: preload) end def pin_all_from(dir, under: nil, to: nil, preload: true) @directories[dir] = MappedDir.new(dir: dir, under: under, path: to, preload: preload) end def preloaded_module_paths(resolver:) cache_as(:preloaded_module_paths) do - resolve_asset_paths(expanded_preloading_files_and_directories, resolver: resolver).values + resolve_asset_paths(expanded_preloading_packages_and_directories, resolver: resolver).values end end def to_json(resolver:) cache_as(:json) do - { "imports" => resolve_asset_paths(expanded_files_and_directories, resolver: resolver) }.to_json + JSON.pretty_generate({ "imports" => resolve_asset_paths(expanded_packages_and_directories, resolver: resolver) }) end end private - MappedFile = Struct.new(:name, :path, :preload, keyword_init: true) MappedDir = Struct.new(:dir, :path, :under, :preload, keyword_init: true) + MappedFile = Struct.new(:name, :path, :preload, keyword_init: true) def cache_as(name) if (cached && result = instance_variable_get("@cached_#{name}")) result else @@ -51,15 +64,15 @@ nil end end.compact end - def expanded_preloading_files_and_directories - expanded_files_and_directories.select { |name, mapping| mapping.preload } + def expanded_preloading_packages_and_directories + expanded_packages_and_directories.select { |name, mapping| mapping.preload } end - def expanded_files_and_directories - @files.dup.tap { |expanded| expand_directories_into expanded } + def expanded_packages_and_directories + @packages.dup.tap { |expanded| expand_directories_into expanded } end def expand_directories_into(paths) @directories.values.each do |mapping| if (absolute_path = absolute_root_of(mapping.dir)).exist?