Module: DeepCover::Reporter::Tree::Util

Extended by:
Util
Included in:
Util
Defined in:
lib/deep_cover/reporter/tree/util.rb

Overview

Utility functions to deal with trees

Instance Method Summary collapse

Instance Method Details

#deep_merge(trees) ⇒ Object

[{b: {c: { } } }

{a: {b: {d: {} } } }]

> {b: {c: {, d: {} }}}



53
54
55
56
57
# File 'lib/deep_cover/reporter/tree/util.rb', line 53

def deep_merge(trees)
  trees.inject({}) do |result, h|
    result.merge(h) { |k, val, val_b| deep_merge([val, val_b]) }
  end
end

#list_to_twig(items) ⇒ Object

A twig is a tree with only single branches

a, b, c

>

{a: {b: {c: {} } } }


42
43
44
45
46
47
48
# File 'lib/deep_cover/reporter/tree/util.rb', line 42

def list_to_twig(items)
  result = {}
  items.inject(result) do |parent, value|
    parent[value] = {}
  end
  result
end

#path_to_partial_paths(path) ⇒ Object

‘some/example/path’ => %w[some example path]



35
36
37
# File 'lib/deep_cover/reporter/tree/util.rb', line 35

def path_to_partial_paths(path)
  path.to_s.split('/')
end

#paths_to_tree(paths) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/deep_cover/reporter/tree/util.rb', line 25

def paths_to_tree(paths)
  twigs = paths.map do |path|
    partials = path_to_partial_paths(path)
    list_to_twig(partials)
  end
  tree = deep_merge(twigs)
  simplify(tree)
end

#populate(tree, dir = '', &block) ⇒ Object

{b: {}} => [ra, rb] where rb = yield(‘a/b’, ‘b’, []) and ra = yield(‘a’, ‘a’, [rb])



75
76
77
78
79
80
81
82
# File 'lib/deep_cover/reporter/tree/util.rb', line 75

def populate(tree, dir = '', &block)
  return to_enum(__method__, tree, dir) unless block_given?
  tree.map do |path, children_hash|
    full_path = [dir, path].join
    children = populate(children_hash, "#{full_path}/", &block)
    yield full_path, path, children
  end
end

#populate_from_map(tree:, map:, merge:) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/deep_cover/reporter/tree/util.rb', line 10

def populate_from_map(tree:, map:, merge:)
  return to_enum(__method__, tree: tree, map: map, merge: merge) unless block_given?
  final_results, _final_data = populate(tree) do |full_path, partial_path, children|
    if children.empty?
      data = map.fetch(full_path)
    else
      child_results, child_data = children.transpose
      data = merge.call(child_data)
    end
    result = yield full_path, partial_path, data, child_results || []
    [result, data]
  end.transpose
  final_results
end

#simplify(tree) ⇒ Object

{b: {c: {, d: {} }}}

> {c: {, d: {} }}



61
62
63
64
65
66
67
68
69
70
# File 'lib/deep_cover/reporter/tree/util.rb', line 61

def simplify(tree)
  tree.map do |key, sub_tree|
    sub_tree = simplify(sub_tree)
    if sub_tree.size == 1
      key2, sub_tree = sub_tree.first
      key = "#{key}/#{key2}"
    end
    [key, sub_tree]
  end.to_h
end