Class: Markbridge::Renderers::Discourse::Builders::ListItemBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/markbridge/renderers/discourse/builders/list_item_builder.rb

Overview

Formats one list item: the marker goes in front of the first line, every other line moves right by the width of the marker. The content is indented as one unit, so nested lists, code fences and HTML blocks inside it keep the shape they already have. Blank lines stay blank; the postprocessor clears whitespace-only lines anyway.

Instance Method Summary collapse

Instance Method Details

#build(content, marker:) ⇒ String

Examples:

builder.build("a\nb", marker: "- ") # => "- a\n  b\n"

Parameters:

  • content (String)

    the item content

  • marker (String)

    the list marker ("- " or "1. ")

Returns:

  • (String)


19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/markbridge/renderers/discourse/builders/list_item_builder.rb', line 19

def build(content, marker:)
  lines = content.split("\n")
  first_line = "#{marker}#{lines.first}"
  return "#{first_line}\n" if lines.size < 2

  indent = " " * marker.length
  # An empty line maps to nil, and join turns that back into
  # an empty line. Indenting it instead would leave a line
  # with nothing but spaces on it.
  rest = lines[1..].map { |line| "#{indent}#{line}" unless line.empty? }
  "#{([first_line] + rest).join("\n")}\n"
end