Skip to content

Commit

Permalink
Method which determines the level while iterating.
Browse files Browse the repository at this point in the history
Signed-off-by: Collective Idea <info@collectiveidea.com>
  • Loading branch information
retoo authored and Collective Idea committed Sep 6, 2009
1 parent b540c21 commit 9fcaaff
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/awesome_nested_set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,30 @@ def rebuild!
set_left_and_rights.call(root_node)
end
end

# Iterates over tree elements and determines the current level in the tree.
# Only accepts default ordering, odering by an other column than lft
# does not work. This method is much more efficent than calling level
# because it doesn't require any additional database queries.
#
# Example:
# Category.each_with_level(Category.root.self_and_descendants) do |o, level|
#
def each_with_level(objects)
path = [nil]
objects.each do |o|
if o.parent_id != path.last
# we are on a new level, did we decent or ascent?
if path.include?(o.parent_id)
# remove wrong wrong tailing paths elements
path.pop while path.last != o.parent_id
else
path << o.parent_id
end
end
yield(o, path.length - 1)
end
end
end

# Mixed into both classes and instances to provide easy access to the column names
Expand Down

0 comments on commit 9fcaaff

Please sign in to comment.