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.
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
-
#add_from_hash(children) ⇒ Array
Instantiate and insert child nodes from data in a Ruby
Hash
. -
#to_h ⇒ Hash
Convert a node and its subtree into a Ruby hash.
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 {}.
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_h ⇒ Hash
Convert a node and its subtree into a Ruby hash.
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 |