Class: Compo::Finders::Root

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/compo/finders/root.rb

Overview

A method object for finding the root of an item in a composite tree

The RootFinder can be used as an Enumerable, where the enumerated items are the path of nodes from the composite to its root, inclusive.

Root finders are not thread-safe.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(leaf) ⇒ Root

Initialises a root finder

Examples:

Initialises a RootFinder

RootFinder.new(composite)

Parameters:

  • leaf (Composite)

    A composite object whose root is to be found.



19
20
21
# File 'lib/compo/finders/root.rb', line 19

def initialize(leaf)
  @leaf = leaf
end

Class Method Details

.find(*args) {|resource| ... } ⇒ Object

Finds the root of a composite object

Examples:

Finds the root of an object

RootFinder.find(composite) { |root| p root }

Parameters:

  • leaf (Composite)

    A composite object whose root is to be found.

Yield Parameters:

  • resource (Object)

    The resource found.

Returns:

  • (Object)

    The return value of the block.



34
35
36
# File 'lib/compo/finders/root.rb', line 34

def self.find(*args, &block)
  new(*args).run(&block)
end

Instance Method Details

#each {|resource| ... } ⇒ void

This method returns an undefined value.

Performs an action on each node in the path to the root

This includes both the root and the object whose root is sought, and runs from the latter to the former.

Examples:

Prints each item from the object to the root.

finder.each { |item| puts item }

Yield Parameters:

  • resource (Object)

    The resource found.



66
67
68
69
70
71
72
73
74
# File 'lib/compo/finders/root.rb', line 66

def each
  node = @leaf
  done = false
  until done
    yield node
    done = node.root?
    node = node.parent
  end
end

#run {|resource| ... } ⇒ Object

Attempts to find the root of this RootFinder’s composite object

When the resource is found, it will be yielded to the attached block.

Examples:

Runs an RootFinder, returning the root unchanged.

finder.run { |root| root }
#=> root

Yield Parameters:

  • resource (Object)

    The resource found.

Returns:

  • (Object)

    The return value of the block.



50
51
52
# File 'lib/compo/finders/root.rb', line 50

def run
  each { |node| yield node if node.root? }
end