Class: WebComponentsRails::HTMLImportProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/web_components_rails/html_import_processor.rb

Overview

Processes web component HTML files that contains imports See also:

https://github.com/rails/sprockets/blob/master/UPGRADING.md
https://github.com/rails/sprockets/blob/3.x/lib/sprockets/directive_processor.rb

Constant Summary collapse

VERSION =
'9'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ HTMLImportProcessor

Returns a new instance of HTMLImportProcessor.



48
49
50
# File 'lib/web_components_rails/html_import_processor.rb', line 48

def initialize(options = {})
  @cache_key = [self.class.name, VERSION, options].freeze
end

Instance Attribute Details

#cache_keyObject (readonly)

Returns the value of attribute cache_key.



46
47
48
# File 'lib/web_components_rails/html_import_processor.rb', line 46

def cache_key
  @cache_key
end

Class Method Details

.cache_keyObject



19
20
21
# File 'lib/web_components_rails/html_import_processor.rb', line 19

def self.cache_key
  instance.cache_key
end

.call(input) ⇒ Object



15
16
17
# File 'lib/web_components_rails/html_import_processor.rb', line 15

def self.call(input)
  instance.call(input)
end

.doc_to_html(doc) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/web_components_rails/html_import_processor.rb', line 23

def self.doc_to_html(doc)
  # Nokogiri/Nokogumbo are hard-coded to URI-escape certain attributes (src, href, action, and a[name]),
  # so we have to put in placeholders, and fix the values in the HTML string output afterwards
  # This doesn't work so well with framework-specific syntax (eg. <foo src="{{bar}}">)
  placeholder_mapping = {}
  %w(src href action).each do |name|
    doc.css("[#{name}]").each do |node|
      # The placeholders are just random strings
      placeholder = SecureRandom.hex(40)
      attr = node.attributes[name]
      placeholder_mapping[placeholder] = attr.value
      attr.value = placeholder
    end
  end
  new_html = doc.to_html
  placeholder_mapping.each do |placeholder, value|
    new_html.sub!(placeholder, value)
  end

  new_html
end

.instanceObject



11
12
13
# File 'lib/web_components_rails/html_import_processor.rb', line 11

def self.instance
  @instance ||= new
end

Instance Method Details

#call(input) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/web_components_rails/html_import_processor.rb', line 52

def call(input)
  # Sprockets::Environment for looking up assets, etc.
  @environment = input[:environment]
  @context = @environment.context_class.new(input)
  @data = input[:data]
  @filename = input[:filename]
  @dirname = File.dirname(@filename)

  @data, paths = process_imports(@data, @dirname)
  paths.each do |path|
    @context.require_asset(path)
  end

  @context..merge(data: @data)
end