Module: Riml::Walkable

Instance Method Summary collapse

Instance Method Details

#child_after(node) ⇒ Object



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

def child_after(node)
  node.next
end

#child_previous_to(node) ⇒ Object



59
60
61
# File 'lib/nodes.rb', line 59

def child_previous_to(node)
  node.previous
end

#each(&block) ⇒ Object Also known as: walk



42
43
44
# File 'lib/nodes.rb', line 42

def each(&block)
  children.each(&block)
end

#index_by_childrenObject



101
102
103
# File 'lib/nodes.rb', line 101

def index_by_children
  parent.children.find_index(self)
end

#index_by_memberObject



91
92
93
94
95
96
97
98
99
# File 'lib/nodes.rb', line 91

def index_by_member
  attrs = parent.members
  attrs.each_with_index do |attr, i|
    if parent.send(attr) == self
      return i
    end
  end
  nil
end

#insert_after(node, new_node) ⇒ Object



85
86
87
88
89
# File 'lib/nodes.rb', line 85

def insert_after(node, new_node)
  idx = children.find_index(node)
  return unless idx
  children.insert(idx + 1, new_node)
end

#insert_before(node, new_node) ⇒ Object



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

def insert_before(node, new_node)
  idx = children.find_index(node)
  return unless idx
  children.insert(idx - 1, new_node)
end

#nextObject



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/nodes.rb', line 69

def next
  idx = index_by_member
  if idx && parent.members[idx + 1]
    attr = parent.members[idx + 1]
    return parent.send(attr)
  else
    idx = index_by_children
    return unless idx
    parent.children.fetch(idx + 1)
  end
end

#previousObject



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/nodes.rb', line 47

def previous
  idx = index_by_member
  if idx && parent.members[idx - 1]
    attr = parent.members[idx - 1]
    return send(attr)
  else
    idx = index_by_children
    return unless idx
    parent.children.fetch(idx - 1)
  end
end

#removeObject



105
106
107
108
109
110
111
112
113
114
# File 'lib/nodes.rb', line 105

def remove
  idx = index_by_member
  if idx
    attr = parent.members[idx]
    parent.send("#{attr}=", nil)
  else
    idx = index_by_children
    parent.children.slice!(idx) if idx
  end
end

#replace_with(new_node) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/nodes.rb', line 116

def replace_with(new_node)
  idx = index_by_member
  if idx
    attr = parent.members[idx]
    new_node.parent = parent
    parent.send("#{attr}=", new_node)
  else
    idx = index_by_children
    return unless idx
    new_node.parent = parent
    parent.children.insert(idx, new_node)
    parent.children.slice!(idx + 1)
  end
end