Module: Hierarchy::ClassMethods

Defined in:
lib/hierarchy.rb

Instance Method Summary collapse

Instance Method Details

#treeifiedHash<ActiveRecord::Base, Hash<...>>

Returns All models organized into a tree structure. Returns a hash where each key is a tree root, and the values are themselves hashes whose keys are the children of the respective model.

Returns:

  • (Hash<ActiveRecord::Base, Hash<...>>)

    All models organized into a tree structure. Returns a hash where each key is a tree root, and the values are themselves hashes whose keys are the children of the respective model.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/hierarchy.rb', line 53

def treeified(root=nil, objects=nil)
  path = root ? root.content.my_path : ''
  root ||= Node.new(nil)
  objects ||= order('id ASC').all.sort_by { |o| [ o.index_path, o.id ] }

  while objects.first and objects.first.path == path
    child = objects.shift
    root << Node.new(child)
  end

  root.children.each do |child|
    treeified child, objects
  end

  return root
end