Class: GovukTechDocs::GovukNunjuckComponenetRenderer

Inherits:
Schmooze::Base
  • Object
show all
Defined in:
lib/govuk_tech_docs/govuk_nunjuck_componenet_renderer.rb

Instance Method Summary collapse

Constructor Details

#initialize(gem_root) ⇒ GovukNunjuckComponenetRenderer

Returns a new instance of GovukNunjuckComponenetRenderer.



7
8
9
10
# File 'lib/govuk_tech_docs/govuk_nunjuck_componenet_renderer.rb', line 7

def initialize(gem_root)
  super(gem_root) # Pass it up to Schmooze so it finds node_modules
  @gem_root = gem_root
end

Instance Method Details

#get_component_template_name(component_name) ⇒ Object



19
20
21
22
23
24
# File 'lib/govuk_tech_docs/govuk_nunjuck_componenet_renderer.rb', line 19

def get_component_template_name(component_name)
  component_name.to_s.delete_prefix("govuk")
              .gsub(/([A-Z]+)([A-Z][a-z])/, '\1-\2') # Handle acronyms like "JSONData"
              .gsub(/([a-z\d])([A-Z])/, '\1-\2')     # Handle standard "CamelCase"
              .downcase
end

#render_govuk_component(component_name, template_data) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/govuk_tech_docs/govuk_nunjuck_componenet_renderer.rb', line 26

def render_govuk_component(component_name, template_data)
  # 1. Logic for search paths belongs here now

  search_paths = [File.join(@gem_root, "node_modules/govuk-frontend/dist")]
  component_template_name = get_component_template_name(component_name)
  # 2. Call the JS method defined above
  nunjucks_template_string = <<~NJK
          {% from "govuk/components/#{component_template_name}/macro.njk" import #{component_name} %}
          {{ #{component_name}(template_data) }}
  NJK
  render_nunjucks_template(nunjucks_template_string, { "template_data" => template_data }, search_paths)
# rubocop:disable Lint/UselessAssignment
rescue StandardError => e
  raise "Could not load GOV.UK component #{component_name} with data #{template_data}."
end