Class: MarkdownFormatter::AST

Inherits:
Object
  • Object
show all
Defined in:
lib/markdown_formatter/ast.rb

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ AST

Returns a new instance of AST.



3
4
5
6
7
# File 'lib/markdown_formatter/ast.rb', line 3

def initialize(source)
  @source = source.dup
  doc = Kramdown::Document.new(source.dup, input: "GFM")
  @ast, @warnings = doc.to_hash_ast
end

Instance Method Details

#to_sObject



42
43
44
45
# File 'lib/markdown_formatter/ast.rb', line 42

def to_s
  traverse
  @source
end

#traverse(parent = [@ast]) ⇒ Object



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
36
37
38
39
40
# File 'lib/markdown_formatter/ast.rb', line 9

def traverse(parent = [@ast])
  parent.each do |node|
    case node[:type]
      when :root
        traverse(node[:children])
      when :blank
        # skip event
      when :p
        str = ASTNode::Paragraph.new(node).to_s

        unless @source.sub!(node.dig(:options, :raw_text).chomp) { |m| str.gsub(/\R(?!\z)/, " ").chomp }
          raise "Parse Failed!!"
        end
      when :ul, :ol, :blockquote
        str = ASTNode::ContainerBlock.new(node).to_s
        unless @source.sub!(node.dig(:options, :raw_text), str)
          raise "Parse Failed!!"
        end
      when :header
        # skip event
      when :hr
        # skip event
      when :codeblock
        # skip event
      when :table
        # TODO: implements Table node.
      else
        pp node
        raise "Unexpected type #{node[:type]}"
    end
  end
end