Module: ActsAsTree::TreeWalker

Defined in:
lib/acts_as_tree.rb

Instance Method Summary collapse

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(_options = {}, level = 0, node = nil, &block)
  options = {:algorithm => :dfs, :where => {}}.update(_options)
  case options[:algorithm]
  when :bfs
    nodes = (node.nil? ? roots : node.children).where(options[:where])
    nodes.each do |child|
      block.call child, level
    end
    nodes.each do |child|
      walk_tree options, level + 1, child, &block
    end
  else
    if node.nil?
      roots.where(options[:where]).each do |root_node|
        walk_tree options, level, root_node, &block
      end
    else
      block.call node, level
      node.children.where(options[:where]).each do |child|
        walk_tree options, level + 1, child, &block
      end
    end
  end
end