Class: BlueDoc::SML::Rules::Heading

Inherits:
Base
  • Object
show all
Defined in:
lib/bluedoc/sml/rules/heading.rb

Constant Summary

Constants inherited from Base

Base::INDENT_PX

Class Method Summary collapse

Methods inherited from Base

to_text

Class Method Details

.match?(node) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
# File 'lib/bluedoc/sml/rules/heading.rb', line 7

def self.match?(node)
  %w[h1 h2 h3 h4 h5 h6].include?(tag_name(node))
end

.to_html(node, opts = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/bluedoc/sml/rules/heading.rb', line 11

def self.to_html(node, opts = {})
  renderer = opts[:renderer]
  title = (renderer.children_to_html(node) || "").strip
  heading_tag = tag_name(node)

  title_length = title.length
  min_length = title_length * 0.3
  words_length = /[a-z0-9]/i.match(title)&.length || 0
  header_id = title.gsub(/[^a-z0-9]+/i, "-").downcase.gsub(/^\-|\-$/, "")
  if title_length - header_id.length > min_length
    header_id = Digest::MD5.hexdigest(title.strip)[0..8]
  end

  attrs = attributes(node)
  nid_attr = name_by_attrs(attrs)

  if title.blank?
    %(<#{heading_tag}#{nid_attr}>#{title}</#{heading_tag}>)
  else
    %(<#{heading_tag} id="#{header_id}"#{nid_attr}><a href="##{header_id}" class="heading-anchor">#</a>#{title}</#{heading_tag}>)
  end
end