Class: MdnQuery::Section

Inherits:
Object
  • Object
show all
Defined in:
lib/mdn_query/section.rb

Overview

A section of an entry of the Mozilla Developer Network documentation.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, level: 1, parent: nil) ⇒ MdnQuery::Section

Creates a new section.



25
26
27
28
29
30
31
# File 'lib/mdn_query/section.rb', line 25

def initialize(name, level: 1, parent: nil)
  @name = escape_html_tags(name)
  @level = level
  @parent = parent
  @text = []
  @children = []
end

Instance Attribute Details

#childrenArray<MdnQuery::Section> (readonly)



5
6
7
# File 'lib/mdn_query/section.rb', line 5

def children
  @children
end

#levelFixnum (readonly)



11
12
13
# File 'lib/mdn_query/section.rb', line 11

def level
  @level
end

#nameString (readonly)



8
9
10
# File 'lib/mdn_query/section.rb', line 8

def name
  @name
end

#parentMdnQuery::Section (readonly)



14
15
16
# File 'lib/mdn_query/section.rb', line 14

def parent
  @parent
end

#textArray<String> (readonly)



17
18
19
# File 'lib/mdn_query/section.rb', line 17

def text
  @text
end

Instance Method Details

#append_code(snippet, language: '') ⇒ void

This method returns an undefined value.

Appends a code segment to the section.

If the code segment is empty (i.e. consists of just whitespaces), it is not appended. The given snippet is embedded in a Markdown code block.

Examples:

Add a JavaScript snippet

append_code("const name = 'My Name';", language: 'javascript')
# adds the following text:
# ```javascript
# const name = 'My Name';
# ```


71
72
73
# File 'lib/mdn_query/section.rb', line 71

def append_code(snippet, language: '')
  @text << "\n```#{language}\n#{snippet}\n```\n" unless text_empty?(snippet)
end

#append_text(text) ⇒ void

This method returns an undefined value.

Appends a text segment to the section.

Spaces before and after newlines are removed. If the text segment is empty (i.e. consists of just whitespaces), it is not appended.



50
51
52
53
54
# File 'lib/mdn_query/section.rb', line 50

def append_text(text)
  trimmed = text.gsub(/\n[[:blank:]]+|[[:blank:]]+\n/, "\n")
  escaped = escape_html_tags(trimmed)
  @text << escaped unless text_empty?(escaped)
end

#create_child(name) ⇒ MdnQuery::Section

Creates a new child section.



37
38
39
40
41
# File 'lib/mdn_query/section.rb', line 37

def create_child(name)
  child = MdnQuery::Section.new(name, parent: self, level: @level + 1)
  @children << child
  child
end

#to_sString

Returns the string representation of the section.



78
79
80
81
82
83
# File 'lib/mdn_query/section.rb', line 78

def to_s
  str = "#{'#' * level} #{name}\n\n#{join_text}\n\n#{join_children}\n"
  str.gsub!(/\n+[[:blank:]]+\n+|\n{3,}/, "\n\n")
  str.strip!
  str
end