class JsTreeBuilder::TreeBuilder

Attributes

to_tree[R]

Public Class Methods

new(s, hn: 1, debug: false) click to toggle source
# File lib/jstreebuilder.rb, line 255
def initialize(s, hn: 1, debug: false)

  @debug, @hn = debug, hn
  html = Kramdown::Document.new(s).to_html
  puts ('html: ' + html.inspect) if @debug
  a = scan_headings(html)
  puts ('a: ' + a.inspect) if @debug
  
  s2 = make_tree(a)
  puts ('s2: ' + s2.inspect) if @debug
  tree = LineTree.new(s2).to_tree
  
  puts ('tree: ' + tree.inspect).debug if @debug
  
  doc = Rexle.new(tree)
  doc.root.each_recursive do |node|
    
    h = node.attributes        
    puts ('h: ' + h.inspect).debug if @debug
    h[:url] = '#' + h[:title].strip.downcase.gsub(' ', '-')
    
  end
  puts ('doc.xml: ' + doc.xml.inspect) if @debug
  
  @to_tree = doc.xml pretty: true

end

Public Instance Methods

make_tree(a, indent=0, hn=@hn) click to toggle source
# File lib/jstreebuilder.rb, line 283
def make_tree(a, indent=0, hn=@hn)
  
  if @debug then
    puts 'inside make_tree'.debug 
    puts ('a: ' + a.inspect).debug
  end
  
  a.map.with_index do |x, i|
    
    puts ('x: ' + x.inspect).debug if @debug
    
    if x.is_a? Array then

      puts 'before make_tree()'.info if @debug
      
      make_tree(x, indent+1, hn)

    else

      next unless x =~ /<h[#{hn}-4]/
      space = i == 0 ? indent-1 : indent
      heading = ('  ' * space) + x[/(?<=\>)[^<]+/]
      puts ('heading: ' + heading.inspect).debug if @debug
      heading

    end

  end.compact.join("\n")

end
scan_headings(s, n=@hn) click to toggle source
# File lib/jstreebuilder.rb, line 314
def scan_headings(s, n=@hn)
  
  s.split(/(?=<h#{n})/).map do |x| 
    x.include?('<h' + (n+1).to_s) ? scan_headings(x, n+1) : x
  end

end