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
-
#from_hash(hash) ⇒ Tree::TreeNode
Factory method builds a TreeNode from a
Hash
.
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 {}.
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 |