Class: Markly::Renderer::Headings

Inherits:
Object
  • Object
show all
Defined in:
lib/markly/renderer/headings.rb

Overview

Extracts headings from a markdown document with unique anchor IDs. Handles duplicate heading text by appending counters (e.g., “deployment”, “deployment-2”, “deployment-3”).

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHeadings

Returns a new instance of Headings.



11
12
13
# File 'lib/markly/renderer/headings.rb', line 11

def initialize
	@ids = {}
end

Class Method Details

.extract(root, min_level: 1, max_level: 6) ⇒ Object

Class method for convenience - creates a new instance and extracts headings.



58
59
60
# File 'lib/markly/renderer/headings.rb', line 58

def self.extract(root, min_level: 1, max_level: 6)
	new.extract(root, min_level: min_level, max_level: max_level)
end

Instance Method Details

#anchor_for(node) ⇒ Object

Generate a unique anchor for a node.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/markly/renderer/headings.rb', line 18

def anchor_for(node)
	base = base_anchor_for(node)
	
	if @ids.key?(base)
		@ids[base] += 1
		"#{base}-#{@ids[base]}"
	else
		@ids[base] = 1
		base
	end
end

#extract(root, min_level: 1, max_level: 6) ⇒ Object

Extract all headings from a document root with unique anchors.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/markly/renderer/headings.rb', line 35

def extract(root, min_level: 1, max_level: 6)
	headings = []
	root.walk do |node|
		if node.type == :header
			level = node.header_level
			next if level < min_level || level > max_level
			
			headings << Heading.new(
				node: node,
				level: level,
				text: node.to_plaintext.chomp,
				anchor: anchor_for(node)
			)
		end
	end
	headings
end