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, context:, keyword: DEFAULT_KEYWORD) ⇒ 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, context:, keyword: DEFAULT_KEYWORD)
  @context = context
  @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

#contextObject (readonly)

Returns the value of attribute context.



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

def context
  @context
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



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

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,
        context: context
      )
    end
    @contents = tail
  end
end

#to_mdObject



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

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