Skip to content

Commit 1007cc8

Browse files
Merge pull request rails#50988 from p8/guides/improve-dom-id-uniqueness
Improve `dom_id` uniqueness in guides
2 parents 6bbfbdb + a720480 commit 1007cc8

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

guides/rails_guides/generator.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def extract_anchors(html)
177177
anchors = Set.new
178178
html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor|
179179
if anchors.member?(anchor)
180-
puts "*** DUPLICATE ID: #{anchor}, please make sure that there are no headings with the same name at the same level."
180+
puts "*** DUPLICATE ID: '#{anchor}', please make sure that there are no headings with the same name at the same level."
181181
else
182182
anchors << anchor
183183
end

guides/rails_guides/markdown.rb

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,15 @@ def render(body)
3535
def dom_id(nodes)
3636
dom_id = dom_id_text(nodes.last.text)
3737

38-
# Fix duplicate node by prefix with its parent node
38+
# Fix duplicate dom_ids by prefixing the parent node dom_id
3939
if @node_ids[dom_id]
4040
if @node_ids[dom_id].size > 1
4141
duplicate_nodes = @node_ids.delete(dom_id)
42-
new_node_id = "#{duplicate_nodes[-2][:id]}-#{duplicate_nodes.last[:id]}"
42+
new_node_id = dom_id_with_parent_node(dom_id, duplicate_nodes[-2])
4343
duplicate_nodes.last[:id] = new_node_id
4444
@node_ids[new_node_id] = duplicate_nodes
4545
end
46-
47-
dom_id = "#{nodes[-2][:id]}-#{dom_id}"
46+
dom_id = dom_id_with_parent_node(dom_id, nodes[-2])
4847
end
4948

5049
@node_ids[dom_id] = nodes
@@ -60,6 +59,14 @@ def dom_id_text(text)
6059
.gsub(/\s+/, "-")
6160
end
6261

62+
def dom_id_with_parent_node(dom_id, parent_node)
63+
if parent_node
64+
[parent_node[:id], dom_id].join("-")
65+
else
66+
dom_id
67+
end
68+
end
69+
6370
def engine
6471
renderer = @epub ? EpubRenderer : Renderer
6572
@engine ||= Redcarpet::Markdown.new(renderer,

0 commit comments

Comments
 (0)