Class: LogBook::Tree

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

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(author: nil, action: nil, request_uuid: nil) ⇒ Tree

Returns a new instance of Tree.



5
6
7
8
9
10
11
# File 'lib/log_book/tree.rb', line 5

def initialize(author: nil, action: nil, request_uuid: nil)
  @nodes = {}
  @depth = 0
  @author = author
  @action = action
  @request_uuid = request_uuid
end

Instance Attribute Details

#actionObject

Returns the value of attribute action.



3
4
5
# File 'lib/log_book/tree.rb', line 3

def action
  @action
end

#authorObject

Returns the value of attribute author.



3
4
5
# File 'lib/log_book/tree.rb', line 3

def author
  @author
end

#depthObject

Returns the value of attribute depth.



3
4
5
# File 'lib/log_book/tree.rb', line 3

def depth
  @depth
end

#nodesObject

Returns the value of attribute nodes.



3
4
5
# File 'lib/log_book/tree.rb', line 3

def nodes
  @nodes
end

#request_uuidObject

Returns the value of attribute request_uuid.



3
4
5
# File 'lib/log_book/tree.rb', line 3

def request_uuid
  @request_uuid
end

Instance Method Details

#add(record) ⇒ Object



13
14
15
16
17
# File 'lib/log_book/tree.rb', line 13

def add(record)
  node = nodes[record.recording_key] ||= Node.new(record)
  add_parent(node, record.parent)
  add_children(node, record.children)
end

#add_child(node, child) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/log_book/tree.rb', line 36

def add_child(node, child)
  return unless child

  child_node = nodes[child.recording_key] ||= Node.new(child)
  child_node.parent = node
  node.children << child_node
  update_depth(node, node.depth)
end

#add_children(node, children) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/log_book/tree.rb', line 28

def add_children(node, children)
  return unless children

  Array.wrap(children).each do |child|
    add_child(node, child)
  end
end

#add_parent(node, parent) ⇒ Object



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

def add_parent(node, parent)
  return unless parent

  parent_node = nodes[parent.recording_key] ||= Node.new(parent)
  node.parent = parent_node
  parent_node.children << node
  update_depth(parent_node, parent_node.depth)
end

#at_depth(depth) ⇒ Object



57
58
59
# File 'lib/log_book/tree.rb', line 57

def at_depth(depth)
  nodes.select { |_, node| node.depth == depth}
end

#records(only_roots: false) ⇒ Object



53
54
55
# File 'lib/log_book/tree.rb', line 53

def records(only_roots: false)
  only_roots ? at_depth(0) : nodes
end

#update_depth(node, depth) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/log_book/tree.rb', line 45

def update_depth(node, depth)
  node.depth = depth
  @depth = [@depth, depth].max
  node.children.each do |child|
    update_depth(child, depth + 1)
  end
end