class Minireq::Gitbook::Reader

Markdown headers structure parser

end

Attributes

items[R]

Public Class Methods

new() click to toggle source
Calls superclass method
# File lib/minireq/gitbook/reader.rb, line 23
def initialize
  @items = Node.new("ROOT") #[]# Node.new("root")
  @pi = nil  #previous item
  @pl = 0    #previous level
  @ci = nil  #current item
  super
end
read(text) click to toggle source

Parse Markdown file @param text [String] text in Markdown @return [Node] by headers structure

# File lib/minireq/gitbook/reader.rb, line 17
def self.read(text)
  parser = Reader.new
  parser.parse(text)
  parser.items
end

Public Instance Methods

markdown_header_level(line) click to toggle source
# File lib/minireq/gitbook/reader.rb, line 52
def markdown_header_level(line)
  9.downto(1) { |l| return l if line.start_with?('#' * l) }
  0
end
markdown_header_title(line) click to toggle source
# File lib/minireq/gitbook/reader.rb, line 57
def markdown_header_title(line)
  line.gsub(/^(#)* /, '')
end
parse(text) click to toggle source
# File lib/minireq/gitbook/reader.rb, line 31
def parse(text)
  header = ''
  paragraph = ''
  quotation = false

  text.each_line do |line|
    if line.start_with?('#') && !quotation
      unless header.empty?
        # hitems << header + paragraph
        parse_header(header)
        paragraph = ''
      end
      header = line
    else
      paragraph << line
      quotation = !quotation if line.start_with?('```')
    end
  end
  parse_header(header) unless header.empty?
end
parse_header(header) click to toggle source
# File lib/minireq/gitbook/reader.rb, line 61
def parse_header(header)
  title = markdown_header_title(header.chomp)
  level = markdown_header_level(header)
  @ci = Node.new(title)
  parent = nil
  if level == 1
    parent = @items
  elsif level > @pl
    parent = @pi
  elsif level < @pl
    parent = @pi
    while parent.level >= level
      parent = parent.parent
    end
  else
    parent = @pi.parent
  end

  parent ||= @items
  parent << @ci

  @pi = @ci
  @pl = level
end