Class: Rundoc::Document

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

Overview

Represents a single rundoc file on disk,

Each document contains one or more fenced code blocks. Those are parsed as ‘FencedCodeBlock` instances and then executed.

Constant Summary collapse

GITHUB_BLOCK =
'^(?<fence>(?<fence_char>~|`){3,})\s*?(?<lang>\w+)?\s*?\n(?<contents>.*?)^\g<fence>\g<fence_char>*\s*?\n?'
CODEBLOCK_REGEX =
/(#{GITHUB_BLOCK})/m
PARTIAL_RESULT =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(contents, context:) ⇒ Document

Returns a new instance of Document.



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

def initialize(contents, context:)
  @context = context
  @contents = contents
  @original = contents.dup
  @stack = []
  partition
  PARTIAL_RESULT.clear
end

Instance Attribute Details

#contentsObject (readonly)

Returns the value of attribute contents.



12
13
14
# File 'lib/rundoc/document.rb', line 12

def contents
  @contents
end

#contextObject (readonly)

Returns the value of attribute context.



12
13
14
# File 'lib/rundoc/document.rb', line 12

def context
  @context
end

#stackObject (readonly)

Returns the value of attribute stack.



12
13
14
# File 'lib/rundoc/document.rb', line 12

def stack
  @stack
end

Class Method Details

.partial_result_to_docObject



40
41
42
43
44
45
# File 'lib/rundoc/document.rb', line 40

def self.partial_result_to_doc
  out = to_doc(result: PARTIAL_RESULT)
  unfinished = FencedCodeBlock.partial_result_to_doc
  out << unfinished if unfinished
  out
end

.to_doc(result:) ⇒ Object



47
48
49
# File 'lib/rundoc/document.rb', line 47

def self.to_doc(result:)
  result.join("")
end

Instance Method Details

#partitionObject

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



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rundoc/document.rb', line 52

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 << FencedCodeBlock.new(
        fence: match[:fence],
        lang: match[:lang],
        code: match[:contents],
        context: context
      )
    end
    @contents = tail
  end
end

#to_mdObject



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

def to_md
  result = []
  @stack.each do |s|
    result << if s.respond_to?(:render)
      s.render
    else
      s
    end
    PARTIAL_RESULT.replace(result)
  end

  self.class.to_doc(result: result)
rescue => e
  File.write("README.md", result.join(""))
  raise e
end