Class: MarkdownFormatter::ASTNode::ListItem

Inherits:
Base
  • Object
show all
Defined in:
lib/markdown_formatter/nodes/list_item.rb

Instance Attribute Summary

Attributes inherited from Base

#node

Instance Method Summary collapse

Constructor Details

#initialize(node, nest_level = 0) ⇒ ListItem

Returns a new instance of ListItem.



4
5
6
7
# File 'lib/markdown_formatter/nodes/list_item.rb', line 4

def initialize(node, nest_level = 0)
  super(node)
  @nest_level = nest_level
end

Instance Method Details

#to_sObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/markdown_formatter/nodes/list_item.rb', line 9

def to_s
  /^(?<prefix>\s*([0-9]+\.|[-+*])\s*)/ =~ node.dig(:options, :raw_text)
  indents = node.dig(:options, :raw_text).lstrip.split(/\R/).map do |line|
    line.match(/^\s+/).to_s
  end

  (prefix + node[:children].map { |c|
    if c[:type] != :blank
      indent, * = indents.shift(c.dig(:options, :raw_text).scan(/\R/).size)
    else
      indents.shift(c[:value].scan(/\R/).size)
    end

    case c[:type]
      when :p
        indent + Paragraph.new(c).to_s.gsub(/\R/, " ").split.join(" ")
      when :blank
        ""
      when :codeblock
        CodeBlock.new(c).to_s.indent(indent.size)
      when :ul
        List.new(c, @nest_level + 1).to_s.chomp
      else
        raise "Unexpected type #{c[:type]}"
    end
  }.join("\n")).indent(@nest_level.zero? ? 0 : 2)
end