Class: Coradoc::Markdown::Heading

Inherits:
Base
  • Object
show all
Defined in:
lib/coradoc/markdown/model/heading.rb

Overview

Heading model representing a Markdown heading (# to ######).

Examples:

Create a heading

heading = Coradoc::Markdown::Heading.new(level: 1, text: "Title")

Instance Method Summary collapse

Methods inherited from Base

#serialize_content, #to_h, #to_md, visit, #visit

Constructor Details

#initialize(level: 1, text: '') ⇒ Heading

Returns a new instance of Heading.



14
15
16
17
18
# File 'lib/coradoc/markdown/model/heading.rb', line 14

def initialize(level: 1, text: '')
  super()
  @level = level
  @text = text
end

Instance Method Details

#auto_idString

Generate an auto ID from the heading text

Examples:

Heading.new(text: "Hello World!").auto_id #=> "hello-world"

Returns:

  • (String)

    A slugified version of the text suitable for use as an ID



25
26
27
28
29
30
31
32
33
34
# File 'lib/coradoc/markdown/model/heading.rb', line 25

def auto_id
  return '' if text.nil? || text.empty?

  # Downcase, replace non-alphanumeric with hyphens, collapse multiple hyphens
  slug = text.to_s
             .downcase
             .gsub(/[^a-z0-9]+/, '-')
             .gsub(/^-+|-+$/, '')
  slug.empty? ? 'section' : slug
end

#heading_idString

Get the ID for this heading (uses explicit id if set, otherwise auto_id)

Returns:

  • (String)

    The ID to use for this heading



39
40
41
# File 'lib/coradoc/markdown/model/heading.rb', line 39

def heading_id
  id || auto_id
end