Skip to content
Permalink
Browse files

added sibling functionality

  • Loading branch information...
dhoss committed Jun 17, 2014
1 parent edd85ee commit 3cf643bb54fc7d3660ec926b693a2a29d4ef6404
Showing with 43 additions and 4 deletions.
  1. +21 −1 lib/treeify.rb
  2. +22 −3 spec/treeify_spec.rb
@@ -49,7 +49,19 @@ def tree_sql_for(instance)
end

def tree_sql_for_ancestors(instance)
"#{tree_sql(instance)}
"WITH RECURSIVE cte (id, path) AS (
SELECT id,
array[id] AS path
FROM #{table_name}
WHERE id = #{instance.id}
UNION ALL
SELECT #{table_name}.id,
cte.path || #{table_name}.id
FROM #{table_name}
JOIN cte ON #{table_name}.parent_id = cte.id
)
SELECT cte.id FROM cte WHERE cte.id != #{instance.id}"
end
end
@@ -65,4 +77,12 @@ def ancestors
def self_and_descendents
self.class.tree_for(self)
end

def is_root?
self.parent_id != nil
end

def siblings
self.class.where(parent_id: self.parent_id) - [self]
end
end
@@ -59,17 +59,36 @@
expect(Node.where(name: "new child node").take).to eq(nil)
end

it "adds children to child nodes"
it "adds children to child nodes" do
root = Node.roots.first
child = root.children.create(name: "new child node")
subchild = child.children.create(name: "new subchild node")
expect(child.children.count).to eq(1)
end

it "has the correct tree after subchildren are added"
it "has the correct tree after subchildren are added" do
tree = Node.roots.first.self_and_descendents
tree.each do |node|
pending "Ancestor count for parent nodes doesn't work yet"
if node.parent_id.nil?
expect(node.ancestors.count).to eq(0)
end
end
end

it "deletes subchildren"

it "re-parents children"

it "has the correct tree after children are re-parented"

it "retrieves siblings"
it "retrieves siblings" do
10.times do |n|
Node.create(name: "sib_#{n}", parent_id: Node.roots.first.id)
end
sib = Node.where(name: "sib_1").take
expect(sib.siblings.count).to eq(12)
end

it "adds siblings"

0 comments on commit 3cf643b

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