class TreeBranch::Processor

This class understands how to take a tree, digest it given a context, set of comparators, and a block, then returns a new tree structure.

Public Instance Methods

process(node, context: nil, comparators: []) { |data, valid_children, context| ... } click to toggle source
# File lib/tree_branch/processor.rb, line 14
def process(node, context: nil, comparators: [], &block)
  return nil if at_least_one_comparator_returns_false?(node.data, context, comparators)

  valid_children = process_children(node.children, context, comparators, &block)

  if block_given?
    yield(node.data, valid_children, context)
  else
    ::TreeBranch::Node.new(node.data)
                      .add(valid_children)
  end
end

Private Instance Methods

at_least_one_comparator_returns_false?(data, context, comparators) click to toggle source
# File lib/tree_branch/processor.rb, line 29
def at_least_one_comparator_returns_false?(data, context, comparators)
  Array(comparators).any? { |c| execute_comparator(c, data, context) == false }
end
execute_comparator(comparator, data, context) click to toggle source
# File lib/tree_branch/processor.rb, line 39
def execute_comparator(comparator, data, context)
  if comparator.is_a?(Proc)
    comparator.call(OpenStruct.new(data), OpenStruct.new(context))
  else
    comparator.new(data: data, context: context).valid?
  end
end
process_children(children, context, comparators, &block) click to toggle source
# File lib/tree_branch/processor.rb, line 33
def process_children(children, context, comparators, &block)
  children.map do |node|
    process(node, context: context, comparators: comparators, &block)
  end.compact
end