document_treeview.rb 1.98 KB
Newer Older
Jiri Strojil's avatar
Jiri Strojil committed
1
2
3
4
5
6
7
8
9
# helps building the json format that is used by the treeview plugin
class DocumentTreeview
  # access the database to identify all the (flat) stored categories and bring
  # them into a tree structure
  def categories_tree
    tree = {}
    category_keys = Document.order(:category1).pluck(:category1, :category2, :category3, :category4)
    category_keys.each do |keys|
      next if keys.first.blank?
10

Jiri Strojil's avatar
Jiri Strojil committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
      tree = a_to_h(keys, tree)
    end
    tree
  end

  # transform the format of categories tree to a format used by the
  # js to display trees in the view
  def category_js_nodes(cat_tree = categories_tree)
    nodes = []
    cat_tree.keys.sort.each do |key|
      node = { text: key, selectable: false, nodes: [] }
      unless cat_tree[key].empty?
        node[:nodes] = category_js_nodes(cat_tree[key])
      end
      nodes << node
    end
    nodes
  end

  # add all documents / links to the document efficient to the js formatted category
  def document_js_nodes
    js_nodes = category_js_nodes
    Document.all.each do |d|
34
      categories = [d.category1, d.category2, d.category3, d.category4].compact
Jiri Strojil's avatar
Jiri Strojil committed
35
36
37
38
39
40
41
42
43
44
      nodes = js_nodes
      categories.each do |category|
        nodes.each do |node|
          if category == node[:text]
            nodes = node[:nodes]
            break
          end
        end
      end
      nodes << {
45
        text: d.title,
Jiri Strojil's avatar
Jiri Strojil committed
46
        href: Rails.application.routes.url_helpers.rails_blob_path(d.file.blob, only_path: true),
47
48
        documentId: d.id,
        icon: 'glyphicon glyphicon-book'
Jiri Strojil's avatar
Jiri Strojil committed
49
50
51
52
53
54
55
56
57
58
59
60
61
      }
      nodes.sort_by! do |node|
        key = node[:nodes] ? '0folder' : '1doc' # prefer folders over documents
        key += node[:text]
        key
      end
    end
    js_nodes
  end

  # helper method to transform category arrays to an array
  def a_to_h(arr, hash)
    return {} if arr.empty? || arr.first.blank?
62

Jiri Strojil's avatar
Jiri Strojil committed
63
64
65
66
67
68
    cur_key = arr.shift
    cur_hash = hash[cur_key]
    hash[cur_key] = cur_hash = {} if cur_hash.nil?
    a_to_h(arr, cur_hash)
    return hash
  end
69
end