Module: Tree::Utils::HashConverter

Included in:
TreeNode
Defined in:
lib/tree/utils/hash_converter.rb

Overview

Provides a utility for marshalling/unmarshalling TreeNode objects to Ruby hash objects.

Author:

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#add_from_hash(children) ⇒ Array

Instantiate and insert child nodes from data in a Ruby Hash

This method is used in conjunction with from_hash to provide a convenient way of building and inserting child nodes present in a Ruby hashes.

This method will instantiate a node instance for each top- level key of the input hash, to be inserted as children of the receiver instance.

Nested hashes are expected and further child nodes will be created and added accordingly. If a hash key is a single value that value will be used as the name for the node. If a hash key is an Array, both node name and content will be populated.

A leaf element of the tree should be represented as a hash key with corresponding value nil or {}.

Examples:

root = Tree::TreeNode.new(:A, "Root content!")
root.add_from_hash({:B => {:D => {}}, [:C, "C content!"] => {}})

Parameters:

  • children (Hash)

    The hash of child subtrees.

Returns:

  • (Array)

    Array of child nodes added

Raises:

  • (ArgumentError)

    This exception is raised if a non-hash is passed.

See Also:

Author:



144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/tree/utils/hash_converter.rb', line 144

def add_from_hash(children)
  raise ArgumentError, 'Argument must be a type of hash'\
                       unless children.is_a?(Hash)

  child_nodes = []
  children.each do |child, grandchildren|
    child_node = self.class.from_hash({ child => grandchildren })
    child_nodes << child_node
    self << child_node
  end

  child_nodes
end

#to_hHash

Convert a node and its subtree into a Ruby hash.

Examples:

root = Tree::TreeNode.new(:root, "root content")
root << Tree::TreeNode.new(:child1, "child1 content")
root << Tree::TreeNode.new(:child2, "child2 content")
root.to_h # => {[:root, "root content"] =>
                     { [:child1, "child1 content"] =>
                                {}, [:child2, "child2 content"] => {}}}

Returns:

  • (Hash)

    Hash representation of tree.

Author:



169
170
171
172
173
174
175
176
177
178
# File 'lib/tree/utils/hash_converter.rb', line 169

def to_h
  key = content? ? [name, content] : name

  children_hash = {}
  children do |child|
    children_hash.merge! child.to_h
  end

  { key => children_hash }
end