Class: HashTree::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_tree.rb

Overview

The base Node type for HashTree implementations. It is not supposed to be called from user-code

Direct Known Subclasses

Map, Set

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent, key) ⇒ Node

Returns a new instance of Node.



28
29
30
31
# File 'lib/hash_tree.rb', line 28

def initialize(parent, key)
  @children = {}
  parent&.do_attach(key, self)
end

Instance Attribute Details

#childrenObject (readonly)

Hash from key to child node



26
27
28
# File 'lib/hash_tree.rb', line 26

def children
  @children
end

#parentObject (readonly)

Parent node. nil for the root node



23
24
25
# File 'lib/hash_tree.rb', line 23

def parent
  @parent
end

Instance Method Details

#[](key) ⇒ Object

Lookup node by key



50
# File 'lib/hash_tree.rb', line 50

def [](key) @children[key] end

#ancestors(include_self = false) ⇒ Object

List of parents from the root element down to parent. If include_self is true, also include self as the last element



66
67
68
# File 'lib/hash_tree.rb', line 66

def ancestors(include_self = false)
  (@ancestors ||= parents(false).reverse) + (include_self ? [self] : [])
end

#attach(key, child) ⇒ Object

Attach a child to self

Implementation is in #do_attach to share code with HashTree::Set#attach that only takes one parameters



37
# File 'lib/hash_tree.rb', line 37

def attach(key, child) do_attach(key, child) end

#detach(key, ignore_not_attached: false) ⇒ Object

Detach a child from self



40
41
42
43
44
45
46
47
# File 'lib/hash_tree.rb', line 40

def detach(key, ignore_not_attached: false)
  @children.key?(key) or raise Error, "Non-existing child key: #{key.inspect}"
  child = children[key]
  ignore_not_attached || child.parent or raise Error, "Child is not attached"
  child.instance_variable_set(:@parent, nil)
  @children.delete(key)
  child.send(:clear_cached_properties)
end

#dot(path) ⇒ Object

Recursively lookup object by dot-separated list of keys

Note that for this to work, keys may not contain a dots (‘.’)



73
74
75
76
77
# File 'lib/hash_tree.rb', line 73

def dot(path)
  path.split(".").inject(self) { |a,e| 
    a[e] or raise Error, "Can't lookup '#{e}' in #{a.path.inspect}" 
  }
end

#key?(key) ⇒ Boolean

Returns true iff key is included in children

Returns:

  • (Boolean)


53
# File 'lib/hash_tree.rb', line 53

def key?(key) @children.key?(key) end

#parents(include_self = false) ⇒ Object

List of parents up to the root element. If include_self is true, also include self as the first element



60
61
62
# File 'lib/hash_tree.rb', line 60

def parents(include_self = false)
  (include_self ? [self] : []) + (@parents ||= (parent&.parents(true) || []))
end

#rootObject

The root object or self if parent is nil



56
# File 'lib/hash_tree.rb', line 56

def root() @root ||= parents.last || self end