Method: Jinx::Visitor#filter

Defined in:
lib/jinx/helpers/visitor.rb

#filter {|parent, children| ... } ⇒ Visitor

Returns a new Visitor which determines which nodes to visit by applying the given block to this visitor. The filter block arguments consist of a parent node and an array of children nodes for the parent. The block can return nil, a single node to visit or a collection of nodes to visit.

Examples:

visitor = Jinx::Visitor.new { |person| person.children }
# Joe has age 55 and children aged 17 and 24, who have children aged [1] and [6, 3], resp.
visitor.to_enum(joe) { |person| person.age } #=> [55, 20, 1, 24, 6, 3]
# The filter navigates to the children sorted by age of parents 21 or older.
filter = visitor.filter { |parent, children| children.sort { |c1, c2| c1.age <=> c2.age } if parent.age >= 21 }
filter.to_enum(joe) { |person| person.age } #=> [55, 24, 3, 6]

Yields:

  • (parent, children)

    the filter to select which of the children to visit next

Yield Parameters:

  • parent

    the currently visited node

  • children (Array)

    the nodes slated by this visitor to visit next

Raises:

  • (ArgumentError)

    if a block is not given to this method



186
187
188
189
# File 'lib/jinx/helpers/visitor.rb', line 186

def filter
  raise ArgumentError.new("A filter block is not given to the visitor filter method") unless block_given?
  self.class.new(@options) { |node| yield(node, node_children(node)) }
end