Module: ActsAsTree::TreeWalker
- Defined in:
- lib/acts_as_tree.rb
Instance Method Summary collapse
-
#walk_tree(_options = {}, level = 0, node = nil, &block) ⇒ Object
Traverse the tree and call a block with the current node and current depth-level.
Instance Method Details
#walk_tree(_options = {}, level = 0, node = nil, &block) ⇒ Object
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 %>
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/acts_as_tree.rb', line 188 def walk_tree( = {}, level = 0, node = nil, &block) = {:algorithm => :dfs, :where => {}}.update() case [:algorithm] when :bfs nodes = (node.nil? ? roots : node.children).where([:where]) nodes.each do |child| block.call child, level end nodes.each do |child| walk_tree , level + 1, child, &block end else if node.nil? roots.where([:where]).each do |root_node| walk_tree , level, root_node, &block end else block.call node, level node.children.where([:where]).each do |child| walk_tree , level + 1, child, &block end end end end |