Class: HoTModuLe::ComponentRenderer

Inherits:
Bridgetown::Builder
  • Object
show all
Defined in:
lib/hot_module/component_renderer.rb

Instance Method Summary collapse

Instance Method Details

#buildObject



5
6
7
# File 'lib/hot_module/component_renderer.rb', line 5

def build
  render_html_modules
end

#render_html_modulesObject

rubocop:todo Metrics



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hot_module/component_renderer.rb', line 10

def render_html_modules
  inspect_html do |doc, resource|
    view_context = Bridgetown::ERBView.new(resource)

    HoTModuLe.registered_elements.each do |component|
      tag_name = component.tag_name
      doc.xpath("//#{tag_name}").reverse.each do |node|
        if node["hmod:ignore"]
          node.remove_attribute("hmod:ignore")
          next
        end

        attrs = node.attributes.transform_values(&:value)
        attrs.reject! { |k| k.start_with?("hmod:") }

        new_attrs = {}
        attrs.each do |k, v|
          next unless k.start_with?("arg:")

          new_key = k.delete_prefix("arg:")
          attrs.delete(k)
          new_attrs[new_key] = resource.instance_eval(v)
        end
        attrs.merge!(new_attrs)
        attrs.transform_keys!(&:to_sym)

        new_node = node.replace(
          component.new(**attrs).render_in(view_context, rendering_mode: :node) { node.children }
        )
        new_node.remove_attribute("hmod:ignore")
      end
    rescue StandardError => e
      Bridgetown.logger.error "Unable to render <#{tag_name}> (#{component}) in #{resource.path}"
      raise e
    end
  end
end