Skip to content
Permalink
Browse files

implemented tree structure and added tests

  • Loading branch information...
dhoss committed Oct 9, 2014
1 parent 94b95a5 commit c1dbe262d64c62053f4881a566e17a4d550f7151
Showing with 56 additions and 4 deletions.
  1. +26 −0 lib/treeify.rb
  2. +4 −4 spec/spec_helper.rb
  3. +26 −0 spec/treeify_spec.rb
@@ -85,4 +85,30 @@ def is_root?
def siblings
self.class.where(parent_id: self.parent_id) - [self]
end

def descendent_tree
# give build_tree an array of hashes with the AR objects serialized into a hash
build_tree(descendents.to_a.map(&:serializable_hash))
end

def build_tree(data)
# turn our AoH into a hash where we've mapped the ID column
# to the rest of the hash + a comments array for nested comments
nested_hash = Hash[data.map{|e| [e['id'], e.merge('children' => [])]}]

# if we have a parent ID, grab all the comments
# associated with that parent and push them into the comments array
nested_hash.each do |id, item|
parent = nested_hash[item['parent_id']]
parent['children'] << item if parent
end

# return the values of our nested hash, ie our actual comment hash data
# reject any descendents whose parent ID already exists in the main hash so we don't
# get orphaned descendents listed as their own comment

nested_hash.reject{|id, item|
nested_hash.has_key? item['parent_id']
}.values
end
end
@@ -18,7 +18,7 @@

class Node < ActiveRecord::Base
include Treeify
config({:cols => [:name]})
config({cols: [:name]})

validates_uniqueness_of :name
validates_uniqueness_of :parent_id, :scope=> :id
@@ -35,7 +35,7 @@ def up
add_index :nodes, [:parent_id, :id], :unique => true
end

def down
def down
drop_table :nodes
end
end
@@ -52,9 +52,9 @@ def down

3.times do |i|
nodes[i] = []
parent = Node.create(:name => "root_#{i}")
parent = Node.create(name: "root_#{i}")
50.times do |j|
node = Node.new(:name => "node_#{i}_#{j}")
node = Node.new(name: "node_#{i}_#{j}")
_parent = nodes[i][rand(nodes[i].size)] || parent
node.parent_id = _parent.id
node.save
@@ -96,6 +96,32 @@

it "deletes siblings"

it "builds the descendents_tree properly" do
parent = Node.create(name: "tree root")
parent.children << Node.new(name: "child 1")
parent.children.first.children << Node.new(name: "child 2")
p "CHILDREN"
pp parent.descendent_tree
child = parent.children.first
subchild = child.children.first
expect(parent.descendent_tree).to match_array([
{
"id" => child.id,
"parent_id" => parent.id,
"name" => child.name,
"children" => [
{
"id" => subchild.id,
"parent_id" => child.id,
"name" => subchild.name,
"children" => []
}
]
}
])
end



end
end

0 comments on commit c1dbe26

Please sign in to comment.
You can’t perform that action at this time.