Class: JsTreeBuilder::TreeBuilder

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(s, hn: 1, debug: false) ⇒ TreeBuilder

Returns a new instance of TreeBuilder.



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# 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

Instance Attribute Details

#to_treeObject (readonly)

Returns the value of attribute to_tree.



253
254
255
# File 'lib/jstreebuilder.rb', line 253

def to_tree
  @to_tree
end

Instance Method Details

#make_tree(a, indent = 0, hn = @hn) ⇒ Object



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# 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) ⇒ Object



314
315
316
317
318
319
320
# 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