Module: ActsAsTree::TreeWalker

Defined in:
lib/acts_as_tree.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(mod) ⇒ Object


223
224
225
226
227
228
229
230
231
# File 'lib/acts_as_tree.rb', line 223

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

Instance Method Details

#walk_tree(options = {}, &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 %>

There is also a walk_tree instance method that starts walking from the node it is called on.


217
218
219
220
221
# File 'lib/acts_as_tree.rb', line 217

def walk_tree(options = {}, &block)
  algorithm = options.fetch :algorithm, :dfs
  where = options.fetch :where, {}
  send("walk_tree_#{algorithm}", where, &block)
end