Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Method which determines the level while iterating.

Signed-off-by: Collective Idea <info@collectiveidea.com>
  • Loading branch information...
commit 9fcaaff3d6b351b11c4b40dc1f3e37f33d0a8cbe 1 parent b540c21
@retoo retoo authored Collective Idea committed
Showing with 24 additions and 0 deletions.
  1. +24 −0 lib/awesome_nested_set.rb
View
24 lib/awesome_nested_set.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.