Module: Gitgo::Helper::Utils
- Included in:
- Format
- Defined in:
- lib/gitgo/helper/utils.rb
Class Method Summary collapse
-
.collapse(array, result = []) ⇒ Object
Collapses an nested array hierarchy such that nesting is only preserved for existing, and not just potential, branches:.
-
.flatten(tree) ⇒ Object
Flattens a hash of (parent, [children]) pairs.
- .render(nodes, io = [], list_open = '<ul>', list_close = '</ul>', item_open = '<li>', item_close = '</li>', indent = '', newline = "\n", &block) ⇒ Object
Class Method Details
.collapse(array, result = []) ⇒ Object
Collapses an nested array hierarchy such that nesting is only preserved for existing, and not just potential, branches:
collapse(["a", ["b", ["c"]]]) # => ["a", "b", "c"]
collapse(["a", ["b", ["c"], ["d", ["e"]]]]) # => ["a", "b", ["c"], ["d", "e"]]
43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/gitgo/helper/utils.rb', line 43 def collapse(array, result=[]) result << array.at(0) if (length = array.length) == 2 collapse(array.at(1), result) else 1.upto(length-1) do |i| result << collapse(array.at(i)) end end result end |
.flatten(tree) ⇒ Object
Flattens a hash of (parent, [children]) pairs. For example:
tree = {
"a" => ["b"],
"b" => ["c", "d"],
"c" => [],
"d" => ["e"],
"e" => []
}
flatten(tree)
# => {
# "a" => ["a", ["b", ["c"], ["d", ["e"]]]],
# "b" => ["b", ["c"], ["d", ["e"]]],
# "c" => ["c"],
# "d" => ["d", ["e"]],
# "e" => ["e"]
# }
Note that the flattened hash re-uses the array values, such that modifiying the “b” value will propagate to the “a” value.
27 28 29 30 31 32 33 34 35 |
# File 'lib/gitgo/helper/utils.rb', line 27 def flatten(tree) tree.each_pair do |parent, children| next unless children children.collect! {|child| tree[child] } children.unshift(parent) end tree end |
.render(nodes, io = [], list_open = '<ul>', list_close = '</ul>', item_open = '<li>', item_close = '</li>', indent = '', newline = "\n", &block) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/gitgo/helper/utils.rb', line 57 def render(nodes, io=[], list_open='<ul>', list_close='</ul>', item_open='<li>', item_close='</li>', indent='', newline="\n", &block) io << indent io << list_open io << newline nodes.each do |node| io << indent io << item_open if node.kind_of?(Array) io << newline render(node, io, list_open, list_close, item_open, item_close, indent + ' ', newline, &block) io << newline io << indent else io << (block_given? ? yield(node) : node) end io << item_close io << newline end io << indent io << list_close io end |