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.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/jstreebuilder.rb', line 180

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.



178
179
180
# File 'lib/jstreebuilder.rb', line 178

def to_tree
  @to_tree
end

Instance Method Details

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



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/jstreebuilder.rb', line 208

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



239
240
241
242
243
244
245
# File 'lib/jstreebuilder.rb', line 239

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