module ActsAsTree::TreeWalker
Public Class Methods
extended(mod)
click to toggle source
# 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
Public Instance Methods
walk_tree(options = {}, &block)
click to toggle source
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
Private Instance Methods
walk_tree_bfs(where = {}, node = nil, level = -1) { |child, level + 1| ... }
click to toggle source
# File lib/acts_as_tree.rb, line 231 def walk_tree_bfs(where = {}, node = nil, level = -1, &block) nodes = (node.nil? ? roots : node.children).where(where) nodes.each { |child| yield(child, level + 1) } nodes.each { |child| walk_tree_bfs where, child, level + 1, &block } end
walk_tree_dfs(where = {}, node = nil, level = -1) { |node, level| ... }
click to toggle source
# File lib/acts_as_tree.rb, line 237 def walk_tree_dfs(where = {}, node = nil, level = -1, &block) yield(node, level) unless level == -1 nodes = (node.nil? ? roots : node.children).where(where) nodes.each { |child| walk_tree_dfs where, child, level + 1, &block } end