Module: Eco::Data::Locations::NodeBase::Treeify

Includes:
Language::AuxiliarLogger
Included in:
Builder, Parsing, Serial
Defined in:
lib/eco/data/locations/node_base/treeify.rb

Overview

Note:

expects nodes to have these properties:

  1. id, name and parentId
  2. parent
  3. tracked_level

Generic treeifier

Instance Attribute Summary

Attributes included from Language::AuxiliarLogger

#logger

Instance Method Summary collapse

Methods included from Language::AuxiliarLogger

#log

Instance Method Details

#serialize_node(node, parent_id: :unused) {|node, json| ... } ⇒ Object

Yields:

  • (node, json)

    optional custom serializer

Yield Parameters:

  • node (Node)

    the node that is being serialized

  • json (Hash)

    the default serialization

Yield Returns:

  • (Hash)

    the serialized Node

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
# File 'lib/eco/data/locations/node_base/treeify.rb', line 14

def serialize_node(node, parent_id: :unused)
  msg = "Expecting Eco::Data::Locations::NodeBase. Given: #{node.class}"
  raise ArgumentError, msg unless node.is_a?(Eco::Data::Locations::NodeBase)

  node.node_hash.tap do |json|
    json.merge!({"parent_id" => parent_id}) unless parent_id == :unused
    json.merge!(yield(node, json))          if block_given?
  end
end

#treeify(nodes, skipped: [], unlinked_trees: []) {|NodeBase| ... } ⇒ Array<Hash>

Note:

if block is no given, it auto-detects the serializer block.

Returns a hierarchical tree of nested Hashes via nodes key.

Yields:

Yield Returns:

  • (Hash)

    custom hash model when treeifying (allows to set more keys/properties).

Returns:

  • (Array<Hash>)

    a hierarchical tree of nested Hashes via nodes key.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/eco/data/locations/node_base/treeify.rb', line 29

def treeify(nodes, skipped: [], unlinked_trees: [], &block)
  return [] if nodes.empty?
  block  ||= nodes.first.class.serializer
  done_ids = {}
  warns    = []
  parents  = parents_hash(nodes)
  get_children(
    nil,                parents,
    done_ids: done_ids, skipped: skipped,
    warns: warns,       &block
  ).tap do |tree|
    check_results(
      tree,             nodes,
      parents,          done_ids:       done_ids,
      skipped: skipped, unlinked_trees: unlinked_trees,
      warns:   warns,   &block
    )
    log(:warn) { warns.join("\n") } unless warns.empty?
  end
end