Module: Tree::Utils::HashConverter::ClassMethods

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

Overview

Methods in ClassMethods will be added as class methods on any class mixing in the Tree::Utils::HashConverter module.

Instance Method Summary collapse

Instance Method Details

#from_hash(hash) ⇒ Tree::TreeNode

Factory method builds a TreeNode from a Hash.

This method will interpret each key of your Hash as a TreeNode. Nested hashes are expected and child nodes will be 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:

TreeNode.from_hash({:A => {:B => {}, :C => {:D => {}, :E => {}}}})
# would be parsed into the following tree structure:
#    A
#   / \
#  B   C
#     / \
#    D   E

# The same tree would result from this nil-terminated Hash
{:A => {:B => nil, :C => {:D => nil, :E => nil}}}

# A tree with equivalent structure but with content present for
# nodes A and D could be built from a hash like this:
{[:A, "A content"] => {:B => {},
                       :C => { [:D, "D content"] => {},
                                :E => {}  }}}

Parameters:

  • hash (Hash)

    Hash to build tree from.

Returns:

Raises:

  • (ArgumentError)

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

  • (ArgumentError)

    This exception is raised if the hash has multiple top-level elements.

  • (ArgumentError)

    This exception is raised if the hash contains values that are not hashes or nils.

Author:



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/tree/utils/hash_converter.rb', line 100

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

  raise ArgumentError, 'Hash must have one top-level element'\
                       if hash.size != 1

  root, children = hash.first

  raise ArgumentError, 'Invalid child. Must be nil or hash.'\
                        unless [Hash, NilClass].any? { |c| children.is_a? c }

  node = new(*root)
  node.add_from_hash(children) unless children.nil?
  node
end