Sha256: c4782e584acdc63e2031a5e853800cd27d5923787a3a17d98858e6b4c0a071c1

Contents?: true

Size: 698 Bytes

Versions: 8

Compression:

Stored size: 698 Bytes

Contents

module Dirtree
  # tree node, it has a name and children of the same type
  class Node
    attr_reader :name, :children

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

    # insert a node by its path, path is an array of names (Strings)
    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

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

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
dirtree-1.0.0 lib/dirtree/node.rb
dirtree-0.6.1 lib/dirtree/node.rb
dirtree-0.6.0 lib/dirtree/node.rb
dirtree-0.5.0 lib/dirtree/node.rb
dirtree-0.4.0 lib/dirtree/node.rb
dirtree-0.3.0 lib/dirtree/node.rb
dirtree-0.2.0 lib/dirtree/node.rb
dirtree-0.1.0 lib/dirtree/node.rb