Module: Tenon::TreeHelper

Defined in:
app/helpers/tenon/tree_helper.rb

Instance Method Summary collapse

Instance Method Details

#nested_li(objects, &block) ⇒ Object



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
# File 'app/helpers/tenon/tree_helper.rb', line 3

def nested_li(objects, &block)
  # This code is a frightmare.  I didn't write it I swear.
  objects = objects.order(:lft) if objects.is_a? Class

  return '' if objects.size == 0

  output = %(<li class='top' data-record-id="#{objects.first.id}">\n<div class='item-content'>\n)
  path = [nil]

  objects.each_with_index do |o, i|
    if o.parent_id != path.last
      # We are on a new level, did we decend or ascend?
      if path.include?(o.parent_id)
        # Remove wrong wrong tailing paths elements
        while path.last != o.parent_id
          path.pop
          output << %(
</li>
</ul>)
        end

        if o.parent_id
          output << %(\n</li>\n<li data-record-id="#{o.id}" class="subpage">\n)
        else
          output << %(\n</li>\n<li data-record-id="#{o.id}" class="top">\n<div class="item-content">\n)
        end
      else
        path << o.parent_id
        output << %(\n<ul class="subpages">\n<li class="subpage" data-record-id="#{o.id}">\n)
      end
    elsif i != 0
      if o.parent_id
        output << %(\n</li>\n<li data-record-id="#{o.id}" class="subpage">\n)
      else
        output << %(\n</li>\n<li data-record-id="#{o.id}" class="top">\n<div class="item-content">\n)
      end
    end
    output << capture(o, path.size - 1, &block)
  end

  path.each do |p|
    if p
      output << %(
</li>
</ul>)
    else
      output << %(
</div>
</li>)
    end
  end

  output.html_safe
end

#recombine_lists(results, children_of, parent_id) ⇒ Object



84
85
86
87
88
89
90
91
# File 'app/helpers/tenon/tree_helper.rb', line 84

def recombine_lists(results, children_of, parent_id)
  if children_of[parent_id]
    children_of[parent_id].each do |o|
      results << o
      recombine_lists(results, children_of, o.id)
    end
  end
end

#sort_list(objects, order) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'app/helpers/tenon/tree_helper.rb', line 62

def sort_list(objects, order)
  objects = objects.order(:lft) if objects.is_a? Class

 # Partition the results
  children_of = {}
  objects.each do |o|
    children_of[o.parent_id] ||= []
    children_of[o.parent_id] << o
  end

  # Sort each sub-list individually
  children_of.each_value do |children|
    children = children.sort_by(&order)
  end

  # Re-join them into a single list
  results = []
  recombine_lists(results, children_of, nil)

  results
end

#sorted_nested_li(objects, order, &block) ⇒ Object



58
59
60
# File 'app/helpers/tenon/tree_helper.rb', line 58

def sorted_nested_li(objects, order, &block)
  nested_li sort_list(objects, order), &block
end