Class: Rundoc::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/rundoc/parser.rb

Constant Summary collapse

DEFAULT_KEYWORD =
":::"
INDENT_BLOCK =
'(?<before_indent>(^\s*$\n|\A)(^(?:[ ]{4}|\t))(?<indent_contents>.*)(?<after_indent>[^\s].*$\n?(?:(?:^\s*$\n?)*^(?:[ ]{4}|\t).*[^\s].*$\n?)*))'
GITHUB_BLOCK =
'^(?<fence>(?<fence_char>~|`){3,})\s*?(?<lang>\w+)?\s*?\n(?<contents>.*?)^\g<fence>\g<fence_char>*\s*?\n'
CODEBLOCK_REGEX =
/(#{GITHUB_BLOCK})/m
COMMAND_REGEX =
->(keyword) {
 /^#{keyword}(?<tag>(\s|=|-|>)?(=|-|>)?)\s*(?<command>(\S)+)\s+(?<statement>.*)$/
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(contents, keyword: DEFAULT_KEYWORD, document_path: nil) ⇒ Parser

Returns a new instance of Parser.



13
14
15
16
17
18
19
20
# File 'lib/rundoc/parser.rb', line 13

def initialize(contents, keyword: DEFAULT_KEYWORD, document_path: nil)
  @document_path = document_path
  @contents = contents
  @original = contents.dup
  @keyword  = keyword
  @stack    = []
  partition
end

Instance Attribute Details

#contentsObject (readonly)

Returns the value of attribute contents.



11
12
13
# File 'lib/rundoc/parser.rb', line 11

def contents
  @contents
end

#keywordObject (readonly)

Returns the value of attribute keyword.



11
12
13
# File 'lib/rundoc/parser.rb', line 11

def keyword
  @keyword
end

#stackObject (readonly)

Returns the value of attribute stack.



11
12
13
# File 'lib/rundoc/parser.rb', line 11

def stack
  @stack
end

Instance Method Details

#partitionObject

split into [before_code, code, after_code], process code, and re-run until tail is empty



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rundoc/parser.rb', line 40

def partition
  until contents.empty?
    head, code, tail = contents.partition(CODEBLOCK_REGEX)
    @stack << head                  unless head.empty?
    unless code.empty?
      match = code.match(CODEBLOCK_REGEX)
      @stack << CodeSection.new(match, keyword: keyword, document_path: @document_path)
    end
    @contents = tail
  end
end

#to_mdObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rundoc/parser.rb', line 22

def to_md
  result = []
  @stack.each do |s|
    if s.respond_to?(:render)
      result << s.render
    else
      result << s
    end
  end
  return result.join("")
rescue Exception => e
  File.open("README.md", "w") do |f|
    f.write(result.join(""))
  end
  raise e
end