Class: Dirtree::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/dirtree/node.rb

Overview

tree node, it has a name and children of the same type

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Node

Returns a new instance of Node.



6
7
8
9
# File 'lib/dirtree/node.rb', line 6

def initialize(name)
  @name = name
  @children = []
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



4
5
6
# File 'lib/dirtree/node.rb', line 4

def children
  @children
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/dirtree/node.rb', line 4

def name
  @name
end

Instance Method Details

#as_jsonObject



27
28
29
30
31
32
# File 'lib/dirtree/node.rb', line 27

def as_json
  {
    name: name,
    children: children.map(&:as_json)
  }
end

#insert(path) ⇒ Object

insert a node by its path, path is an array of names (Strings)



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/dirtree/node.rb', line 12

def insert(path)
  return if path.empty?

  child_name = path.first
  grandchildren = path[1..-1]

  child = @children.find { |current| current.name == child_name }
  unless child
    child = Node.new(child_name)
    @children << child
  end

  child.insert(grandchildren)
end