Created
February 6, 2024 11:37
-
-
Save amkisko/86ad375654ed5b268cc329ba8020994e to your computer and use it in GitHub Desktop.
Rails custom importmaps snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails::Application.send(:attr_accessor, :importmaps) | |
module Importmap::CustomImportmapTagsHelper | |
def javascript_custom_importmap_tags(name, entry_point: "application") | |
importmap = Rails.application.importmaps[name.to_sym] | |
return unless importmap | |
javascript_importmap_tags(entry_point, importmap: importmap) | |
end | |
end | |
ActiveSupport.on_load(:action_controller_base) do | |
helper Importmap::CustomImportmapTagsHelper | |
end | |
class CustomImportmap | |
attr_reader :importmap, :name | |
def initialize(name, path:, assets_paths: nil) | |
@name = name | |
importmap_name = name.to_sym | |
raise ArgumentError, "Importmap #{importmap_name} already exists" if Rails.application.importmaps&.key?(importmap_name) | |
@importmap = Importmap::Map.new | |
importmap.draw(path) | |
if assets_paths | |
importmap.cache_sweeper(watches: assets_paths) | |
Rails.application.config.assets.paths += assets_paths | |
end | |
Rails.application.importmaps ||= {} | |
Rails.application.importmaps[importmap_name] = importmap | |
end | |
def call | |
ActiveSupport.on_load(:action_controller_base) do | |
before_action { importmap.cache_sweeper.execute_if_updated } | |
end | |
end | |
def erb_usage | |
"<%= javascript_custom_importmap_tags(importmap: #{name}) %>" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment