module Tree::Utils::HashConverter

Public Class Methods

included(base) click to toggle source
# File lib/tree/utils/hash_converter.rb, line 44
def self.included(base)
  base.extend(ClassMethods)
end

Public Instance Methods

add_from_hash(children) click to toggle source

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 {}.

@example

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

@author Jen Hamon (www.github.com/jhamon) @param [Hash] children The hash of child subtrees. @raise [ArgumentError] This exception is raised if a non-hash is passed. @return [Array] Array of child nodes added @see ClassMethods#from_hash

# File lib/tree/utils/hash_converter.rb, line 142
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_h() click to toggle source

Convert a node and its subtree into a Ruby hash.

@example

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"] => {}}}

@author Jen Hamon (www.github.com/jhamon) @return [Hash] Hash representation of tree.

# File lib/tree/utils/hash_converter.rb, line 167
def to_h
  key = has_content? ? [name, content] : name

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

  { key => children_hash }
end