Module: Mongoid::Tree::Traversal

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid/tree/traversal.rb

Overview

Mongoid::Tree::Traversal

Mongoid::Tree::Traversal provides a #traverse method to walk through the tree. It supports these traversal methods:

  • depth_first

  • breadth_first

Depth First Traversal

See en.wikipedia.org/wiki/Depth-first_search for a proper description.

Given a tree like:

node1:
 - node2:
   - node3
 - node4:
   - node5
   - node6
 - node7

Traversing the tree using depth first traversal would visit each node in this order:

node1, node2, node3, node4, node5, node6, node7

Breadth First Traversal

See en.wikipedia.org/wiki/Breadth-first_search for a proper description.

Given a tree like:

node1:
  - node2:
    - node5
  - node3:
    - node6
    - node7
  - node4

Traversing the tree using breadth first traversal would visit each node in this order:

node1, node2, node3, node4, node5, node6, node7

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#traverse(type = :depth_first, &block) ⇒ Object

Traverses the tree using the given traversal method (Default is :depth_first) and passes each document node to the block.

See Mongoid::Tree::Traversal for available traversal methods.

Example:

results = []
root.traverse(:depth_first) do |node|
  results << node
end

Raises:

  • (ArgumentError)


97
98
99
100
# File 'lib/mongoid/tree/traversal.rb', line 97

def traverse(type = :depth_first, &block)
  raise ArgumentError, "No block given" unless block_given?
  send("#{type}_traversal", &block)
end