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:, io: $stdout) ⇒ Document

Returns a new instance of Document.



16
17
18
19
20
21
22
23
24
# File 'lib/rundoc/document.rb', line 16

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

Instance Attribute Details

#contentsObject (readonly)

Returns the value of attribute contents.



14
15
16
# File 'lib/rundoc/document.rb', line 14

def contents
  @contents
end

#contextObject (readonly)

Returns the value of attribute context.



14
15
16
# File 'lib/rundoc/document.rb', line 14

def context
  @context
end

#stackObject (readonly)

Returns the value of attribute stack.



14
15
16
# File 'lib/rundoc/document.rb', line 14

def stack
  @stack
end

Class Method Details

.partial_result_to_docObject



43
44
45
46
47
48
# File 'lib/rundoc/document.rb', line 43

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



50
51
52
# File 'lib/rundoc/document.rb', line 50

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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/rundoc/document.rb', line 55

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

#to_mdObject



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

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