Class: Foobara::Util::SubTree

Inherits:
Object
  • Object
show all
Defined in:
foobara-util-0.0.11/lib/foobara/util/tree.rb

Direct Known Subclasses

Tree

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, to_parent = nil, &block) ⇒ SubTree

Returns a new instance of SubTree.



6
7
8
9
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 6

def initialize(value, to_parent = nil, &block)
  self.value = value
  self.to_parent = to_parent.nil? ? block : to_parent.to_proc
end

Instance Attribute Details

#parent_treeObject

Returns the value of attribute parent_tree.



4
5
6
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 4

def parent_tree
  @parent_tree
end

#to_parentObject

Returns the value of attribute to_parent.



4
5
6
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 4

def to_parent
  @to_parent
end

#valueObject

Returns the value of attribute value.



4
5
6
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 4

def value
  @value
end

Instance Method Details

#add(object) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 19

def add(object)
  return if include?(object)

  parent = to_parent.call(object)

  parent_node = if parent
                  node_for(parent) || add(parent)
                else
                  self
                end

  child_tree = SubTree.new(object, to_parent)
  child_tree.parent_tree = parent_node
  parent_node.children_trees << child_tree

  child_tree
end

#children_treesObject



15
16
17
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 15

def children_trees
  @children_trees ||= []
end

#include?(value) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 48

def include?(value)
  !!node_for(value)
end

#node_for(value) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 37

def node_for(value)
  return self if value == self.value

  children_trees.each do |child|
    node = child.node_for(value)
    return node if node
  end

  nil
end

#root?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 11

def root?
  parent_tree.is_a?(Tree)
end

#to_s(to_name, padding: "", last_child: true) ⇒ Object

TODO: try to break this up a bit



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'foobara-util-0.0.11/lib/foobara/util/tree.rb', line 53

def to_s(to_name, padding: "", last_child: true)
  output = StringIO.new
  name = to_name.call(value)

  padding = puts_box(output, name, padding, last_child)

  children = children_trees.sort_by { |child_tree| to_name.call(child_tree.value) }
  last = children.last

  children.each do |child_tree|
    output.puts child_tree.to_s(to_name, padding:, last_child: child_tree == last)
  end

  output.string
end