Class: Fmt::Node

Inherits:
AST::Node
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/fmt/node.rb

Overview

Extends behavior of AST::Node

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, children = [], properties = {urtext: "", source: ""}) ⇒ Node

Constructor



39
40
41
42
43
# File 'lib/fmt/node.rb', line 39

def initialize(type, children = [], properties = {urtext: "", source: ""})
  @properties = properties
  define_properties properties
  super
end

Instance Attribute Details

#propertiesObject (readonly)

: Hash[Symbol, Object]



45
46
47
# File 'lib/fmt/node.rb', line 45

def properties
  @properties
end

Class Method Details

.node_children(node) ⇒ Object

Finds all Node child nodes



14
15
16
17
18
19
20
# File 'lib/fmt/node.rb', line 14

def node_children(node)
  list = []
  node.children.each do |child|
    list << child if child.is_a?(Node)
  end
  list
end

.node_descendants(node) ⇒ Object

Recursively finds all Nodes in the tree



25
26
27
28
29
30
31
32
# File 'lib/fmt/node.rb', line 25

def node_descendants(node)
  list = []
  node.children.each do |child|
    list << child if child.is_a?(Node)
    list.concat node_children(child)
  end
  list
end

Instance Method Details

#dig(*types) ⇒ Object

Recursively searches the tree for a descendant node



63
64
65
66
67
# File 'lib/fmt/node.rb', line 63

def dig(*types)
  node = find(types.shift) if types.any?
  node = node.find(types.shift) while node && types.any?
  node
end

#find(type) ⇒ Object

Finds the first child node of the specified type



72
73
74
75
76
77
# File 'lib/fmt/node.rb', line 72

def find(type)
  case type
  in Symbol then children.find { _1 in [^type, *] }
  in Class then children.find { _1 in ^type }
  end
end

#flattenObject

Flattens Node descendants into a one dimensional array



81
82
83
# File 'lib/fmt/node.rb', line 81

def flatten
  node_descendants.prepend self
end

#select(type) ⇒ Object

Finds all child nodes of the specified type



88
89
90
91
92
93
94
# File 'lib/fmt/node.rb', line 88

def select(type)
  [].concat case type
  in Symbol then children.select { _1 in [^type, *] }
  in Class then children.select { _1 in ^type }
  else []
  end
end

#to_s(squish: false) ⇒ Object

String representation of the node (AST)



99
100
101
102
103
# File 'lib/fmt/node.rb', line 99

def to_s(squish: false)
  value = super()
  return value unless squish
  value.gsub(/\s{2,}/, " ")
end