# File lib/acts_as_tree.rb, line 219 def self.extended(mod) mod.class_eval do def walk_tree(options = {}, &block) algorithm = options.fetch :algorithm, :dfs where = options.fetch :where, {} self.class.send("walk_tree_#{algorithm}", where, self, &block) end end end
Traverse the tree and call a block with the current node and current depth-level.
options:
algorithm: :dfs for depth-first search (default) :bfs for breadth-first search where: AR where statement to filter certain nodes
The given block sets two parameters:
first: The current node second: The current depth-level within the tree
Example of acts_as_tree for model Page (ERB view): <% Page.walk_tree do |page, level| %>
<%= link_to "#{' '*level}#{page.name}", page_path(page) %><br />
<% end %>
There is also a #walk_tree instance method that starts walking from the node it is called on.
# File lib/acts_as_tree.rb, line 213 def walk_tree(options = {}, &block) algorithm = options.fetch :algorithm, :dfs where = options.fetch :where, {} send("walk_tree_#{algorithm}", where, &block) end