Class: TTY::Tree::HashWalker
- Inherits:
-
Object
- Object
- TTY::Tree::HashWalker
- Defined in:
- lib/tty/tree/hash_walker.rb
Overview
Walk and collect nodes from hash data strcture.
Instance Attribute Summary collapse
- #dirs_count ⇒ Object readonly
- #files_count ⇒ Object readonly
- #nodes ⇒ Object readonly
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ HashWalker
constructor
A new instance of HashWalker.
- #traverse(data) ⇒ Object
- #walk(data, parent_path, prefix, level, is_last) ⇒ Object
Constructor Details
permalink #initialize(options = {}) ⇒ HashWalker
Returns a new instance of HashWalker.
19 20 21 22 23 24 25 |
# File 'lib/tty/tree/hash_walker.rb', line 19 def initialize( = {}) @nodes = [] @files_count = 0 @dirs_count = 0 @level = .fetch(:level) { -1 } @file_limit = .fetch(:file_limit) { - 1 } end |
Instance Attribute Details
permalink #dirs_count ⇒ Object (readonly)
17 18 19 |
# File 'lib/tty/tree/hash_walker.rb', line 17 def dirs_count @dirs_count end |
permalink #files_count ⇒ Object (readonly)
15 16 17 |
# File 'lib/tty/tree/hash_walker.rb', line 15 def files_count @files_count end |
permalink #nodes ⇒ Object (readonly)
13 14 15 |
# File 'lib/tty/tree/hash_walker.rb', line 13 def nodes @nodes end |
Instance Method Details
permalink #traverse(data) ⇒ Object
27 28 29 |
# File 'lib/tty/tree/hash_walker.rb', line 27 def traverse(data) walk(data, Pathname.new(''), '', 0, false) end |
permalink #walk(data, parent_path, prefix, level, is_last) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/tty/tree/hash_walker.rb', line 31 def walk(data, parent_path, prefix, level, is_last) node = is_last ? LeafNode : Node case data when Hash return if @level != -1 && level + 1 > @level data.each do |dir, item| dir_node = node.new(dir.to_s, parent_path, prefix, level) @nodes << dir_node @dirs_count += 1 unless dir_node.root? if level > 0 postfix = ':pipe' postfix = ':space' if is_last else postfix = '' end walk(item, parent_path + dir.to_s, prefix + postfix, level + 1, false) end when Array return if @file_limit != -1 && data.size > @file_limit last_data_index = data.size - 1 data.each_with_index do |item, i| last = (last_data_index == i) walk(item, parent_path, prefix, level, last) end else @nodes << node.new(data.to_s, parent_path, prefix, level) @files_count += 1 end end |