hagabaka (owner)

Revisions

gist: 216669 Download_button fork
public
Public Clone URL: git://gist.github.com/216669.git
Embed All Files: show embed
html-tree.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# What's a good way of using HAML to generate an HTML nested list from tree
# data?
 
# Example tree data
# Root is the number 12, the children of any node are the factors of the number
NUMBERS = (2..12).to_a
ROOT = NUMBERS.max
CHILDREN_PROC = proc do |number|
  (NUMBERS - [number]).select {|other_number| number % other_number == 0}
end
 
# Expected html
<<-'END_HTML'
<ul>
<li>12 <ul>
<li>2</li>
<li>3</li>
<li>4 <ul>
<li>2</li>
</ul>
</li>
<li>6 <ul>
<li>2</li>
<li>3</li>
</ul>
</li>
</ul>
</li>
</ul>
END_HTML
 
# My implementation
# Works, but yielding things like :no_children and explicitly writing
# open/close tags in haml is ugly
def tree_traverse(root, children_proc, &block)
  yield(root)
  children = children_proc.call(root)
  if children.empty?
    yield(:no_children)
  else
    yield(:begin_children)
    children.each do |child|
      tree_traverse(child, children_proc, &block)
    end
    yield(:end_children)
  end
end
 
require 'haml'
ENGINE = Haml::Engine.new <<-'END_HAML'
%ul
- tree_traverse(ROOT, CHILDREN_PROC) do |node|
- case node
- when :begin_children
<ul>
- when :end_children
</ul>
</li>
- when :no_children
</li>
- else
== <li>#{node}
END_HAML
puts ENGINE.render