Class: Kube::Ctl::TreeNode

Inherits:
Object
  • Object
show all
Defined in:
lib/kube/ctl/tree_node.rb

Constant Summary collapse

RESOURCE_PARENTS =

Commands whose leaf children are resource types. Non-leaf children (those with their own subtree) remain commands.

%w[
  create
  create/secret
  create/service
  top
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, type:, children: {}) ⇒ TreeNode

Returns a new instance of TreeNode.



17
18
19
20
21
# File 'lib/kube/ctl/tree_node.rb', line 17

def initialize(name:, type:, children: {})
  @name     = name.freeze
  @type     = type
  @children = children.freeze
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



15
16
17
# File 'lib/kube/ctl/tree_node.rb', line 15

def children
  @children
end

#nameObject (readonly)

Returns the value of attribute name.



15
16
17
# File 'lib/kube/ctl/tree_node.rb', line 15

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



15
16
17
# File 'lib/kube/ctl/tree_node.rb', line 15

def type
  @type
end

Class Method Details

.build(hash, parent_path: nil) ⇒ Object

Recursively build a children hash of TreeNodes from the parsed JSON. parent_path tracks position in the tree to determine child types.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/kube/ctl/tree_node.rb', line 28

def self.build(hash, parent_path: nil)
  hash.each_with_object({}) do |(key, subtree), children|
    name         = key.to_s
    current_path = [parent_path, name].compact.join('/')
    leaf         = subtree.empty?

    # Under a resource parent, leaf nodes are resources, non-leaves are commands.
    # Everywhere else, everything is a command.
    child_type = if RESOURCE_PARENTS.include?(parent_path.to_s) && leaf
                   :resource
                 else
                   :command
                 end

    children[name] = new(
      name: name,
      type: child_type,
      children: build(subtree, parent_path: current_path)
    )
  end
end

Instance Method Details

#command?Boolean

Returns:

  • (Boolean)


23
# File 'lib/kube/ctl/tree_node.rb', line 23

def command?  = type == :command

#resource?Boolean

Returns:

  • (Boolean)


24
# File 'lib/kube/ctl/tree_node.rb', line 24

def resource? = type == :resource