Class: Branchtree::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/branchtree/tree.rb

Overview

Represent the branch topology described by a user’s YAML file.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(roots) ⇒ Tree

Returns a new instance of Tree.



16
17
18
# File 'lib/branchtree/tree.rb', line 16

def initialize(roots)
  @roots = roots
end

Instance Attribute Details

#rootsObject (readonly)

Returns the value of attribute roots.



14
15
16
# File 'lib/branchtree/tree.rb', line 14

def roots
  @roots
end

Class Method Details

.load(source) ⇒ Object

Load a tree from the topology described in a YAML file.



9
10
11
12
# File 'lib/branchtree/tree.rb', line 9

def self.load(source)
  doc = YAML.safe_load(File.read(source))
  new(doc.map { |node| Branchtree::Branch.load(node, nil) })
end

Instance Method Details

#breadth_first(&block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/branchtree/tree.rb', line 32

def breadth_first(&block)
  level = 0
  frontier = roots.dup

  until frontier.empty?
    frontier.each do |branch|
      block.call(level, branch)
    end

    level += 1
    frontier = frontier.flat_map(&:children)
  end
end

#depth_first(&block) ⇒ Object



28
29
30
# File 'lib/branchtree/tree.rb', line 28

def depth_first(&block)
  depth_first_from(level: 0, branches: roots, &block)
end

#find_branch(name) ⇒ Object

Locate a known branch in the tree by abbreviated ref name, or return nil if none are found.



21
22
23
24
25
26
# File 'lib/branchtree/tree.rb', line 21

def find_branch(name)
  breadth_first do |level, branch|
    return branch if branch.name == name
  end
  nil
end