Skip to content
This repository has been archived by the owner on Feb 5, 2019. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
Bug fixes for getting index path on parent
  • Loading branch information
RISCfuture committed Nov 11, 2010
1 parent 7f425ca commit 10a0b93
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion LICENSE
@@ -1,4 +1,4 @@
Copyright (c) 2009 Tim Morgan
Copyright (c) 2010 Tim Morgan

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
Expand Down
4 changes: 3 additions & 1 deletion lib/hierarchy.rb
Expand Up @@ -53,7 +53,7 @@ module Hierarchy

base.scope :parent_of, ->(obj) { obj.top_level? ? base.where('false') : base.where(id: obj.index_path.last) }
base.scope :children_of, ->(obj) { base.where(path: obj.my_path) }
base.scope :ancestors_of, ->(obj) { base.where(id: obj.index_path.to_a) }
base.scope :ancestors_of, ->(obj) { obj.top_level? ? base.where('false') : base.where(id: obj.index_path.to_a) }
base.scope :descendants_of, ->(obj) { base.where([ "path <@ ?", obj.my_path ]) }
base.scope :siblings_of, ->(obj) { base.where(path: obj.path) }
base.scope :priority_order, base.order("NLEVEL(path) ASC")
Expand Down Expand Up @@ -109,6 +109,7 @@ def parent=(parent)
# @return [Array] The objects above this one in the hierarchy.

def ancestors(options={})
return [] if top_level?
objects = self.class.ancestors_of(self).scoped(options).group_by(&:id)
index_path.map { |id| objects[id].first }
end
Expand Down Expand Up @@ -160,6 +161,7 @@ def my_path

# @private
def index_path
raise "Can't get index path of top-level object #{self.inspect}" if path.blank?
IndexPath.from_ltree path
end
end
Expand Down
6 changes: 6 additions & 0 deletions spec/hierarchy_spec.rb
Expand Up @@ -107,4 +107,10 @@
parent.should_not be_bottom_level
end
end

describe "#ancestors" do
it "should return an empty array for a top-level object" do
Model.create!.ancestors.should eql([])
end
end
end

0 comments on commit 10a0b93

Please sign in to comment.