Skip to content

Commit

Permalink
added sibling functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
dhoss committed Jun 17, 2014
1 parent edd85ee commit 3cf643b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
22 changes: 21 additions & 1 deletion lib/treeify.rb
Expand Up @@ -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
Expand All @@ -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
25 changes: 22 additions & 3 deletions spec/treeify_spec.rb
Expand Up @@ -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"

Expand Down

0 comments on commit 3cf643b

Please sign in to comment.