Class: Natspec::Parser

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

Instance Method Summary collapse

Constructor Details

#initialize(txt) ⇒ Parser

Returns a new instance of Parser.



40
41
42
# File 'lib/natspec.rb', line 40

def initialize( txt )
  @txt = txt
end

Instance Method Details

#_indent_code_block(sect) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/natspec.rb', line 92

def _indent_code_block( sect )
  ## step 1: indent code blocks
  inside_block = false
  sect.each_with_index do |line,i|
    if line.start_with?( '```' )
       inside_block = !inside_block
    elsif inside_block
        sect[i] = (' '*4) + sect[i]
    else
       ## regular line; keep going
    end
  end
  ## step 2: remove all code block lines
  _strip_code_block( sect )
end

#_strip_code_block(sect) ⇒ Object



88
89
90
# File 'lib/natspec.rb', line 88

def _strip_code_block( sect )
  sect.reject! { |line| line.start_with?( '```' ) }
end

#_strip_empty_leading_lines(sect) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
# File 'lib/natspec.rb', line 121

def _strip_empty_leading_lines( sect )
   loop do
     line = sect[0]
       if line && line.empty?
          sect.shift
       else
          break
       end
   end
   sect
end

#_strip_empty_trailing_lines(sect) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
# File 'lib/natspec.rb', line 109

def _strip_empty_trailing_lines( sect )
   loop do
     line = sect[-1]
       if line && line.empty?
          sect.pop
       else
          break
       end
   end
   sect
end

#parseObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/natspec.rb', line 44

def parse
  head = []
  sections = []

  section = nil
  @txt.each_line do |line|

    line = line.rstrip
    if (m=line.match( /\A[ ]*\#{2}[ ]*(?<heading>.+)[ ]*\z/ ))
      puts "  found heading >#{m[:heading]}<"
      sections << section   if section
      section = [m[:heading],[]]
    elsif (m=line.match(/\A[ ]*\#{1,}/ ))
      puts "   !! ERROR - unsupported heading level in line >#{line}<; sorry"
      exit 1
    else
        if section
          section[1] << line
        else
          head << line
        end
    end
  end

  sections <<  section  if section


  ## pre-process sections
  ##  remove trailing empty lines
  _strip_empty_leading_lines( head )
  _strip_empty_trailing_lines( head )
  _indent_code_block( head )

  sections.each do |heading, lines|
    _strip_empty_leading_lines( lines )
    _strip_empty_trailing_lines( lines )
    _strip_code_block( lines )
  end


  Document.new( head, sections )
end