Class: Railsboot::HeadingWithAnchorComponent

Inherits:
HeadingComponent
  • Object
show all
Defined in:
app/components/railsboot/heading_with_anchor_component.rb

Overview

ViewComponent: renders the heading with anchor block.

Extends HeadingComponent to add a self-referencing anchor
link so a heading can be linked to directly via a URL fragment.

Instance Method Summary collapse

Instance Method Details

#anchor_htmlString

Builds the anchor link element pointing at this heading's own id.

Returns:

  • (String)

    the HTML for the anchor link



10
11
12
# File 'app/components/railsboot/heading_with_anchor_component.rb', line 10

def anchor_html
  link_to "", "##{anchor_id}", class: "heading-anchor", 'aria-label': "Anchor", data: { anchor_icon: "#", turbo: "false" }
end

#anchor_idString

Derives a URL-fragment-safe id from the heading's text content.

Returns:

  • (String)

    parameterized, underscore-separated anchor id



17
18
19
# File 'app/components/railsboot/heading_with_anchor_component.rb', line 17

def anchor_id
  ActionView::Base.full_sanitizer.sanitize(content).parameterize(separator: "_")
end

#before_rendervoid

This method returns an undefined value.

Sets the heading's id attribute to #anchor_id before rendering so
the anchor link target resolves.



25
26
27
# File 'app/components/railsboot/heading_with_anchor_component.rb', line 25

def before_render
  @html_attributes[:id] = anchor_id
end

#callString

Renders the heading with its escaped content followed by the anchor link.

Returns:

  • (String)

    the rendered component HTML



32
33
34
35
36
# File 'app/components/railsboot/heading_with_anchor_component.rb', line 32

def call
  render Railsboot::HeadingComponent.new(**@html_attributes) do
    ERB::Util.html_escape(content).concat(anchor_html.to_s.html_safe)
  end
end