Module: Tree::InternalChildrenArrayImplementation

Includes:
InternalChildrenImplementation
Included in:
ArrayTree
Defined in:
lib/modular_tree/implementations.rb

Overview

TODO: A ChildrenArrayImplementation that defines #insert and #append and adds an optional index argument to #attach

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from InternalChildrenImplementation

#branches, #each_branch

Methods included from NodeProperty

#node, #node_value

Methods included from BranchesProperty

#bare?, #branches, #each_branch

Methods included from InternalImplementation

#node, #node_value, #this

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



168
169
170
# File 'lib/modular_tree/implementations.rb', line 168

def children
  @children
end

Instance Method Details

#append(where, child) ⇒ Object



192
# File 'lib/modular_tree/implementations.rb', line 192

def append(where, child) = insert_append(:append, where, child)

#attach(child) ⇒ Object



177
# File 'lib/modular_tree/implementations.rb', line 177

def attach(child) = @children << child

#detach(arg) ⇒ Object



178
179
180
181
182
183
# File 'lib/modular_tree/implementations.rb', line 178

def detach(arg)
  key = arg.is_a?(Integer) ? arg : @children.index(arg)
  child = @children.delete_at(key) or raise ArgumentError, "Can't find object"
  child.send(:instance_variable_set, :@parent, nil)
  child
end

#each_child(&block) ⇒ Object



175
# File 'lib/modular_tree/implementations.rb', line 175

def each_child(&block) = @children.map(&block)

#initialize(_parent) ⇒ Object



170
171
172
173
# File 'lib/modular_tree/implementations.rb', line 170

def initialize(_parent)
  @children = []
  super
end

#insert(where, child) ⇒ Object

Can be used with any array implementation. where is either an Integer index or an object

TODO: Rename #attach. #insert & #append are Enumerable operations

TODO: Default where argument - insert: 0, append: -1



191
# File 'lib/modular_tree/implementations.rb', line 191

def insert(where, child) = insert_append(:insert, where, child)

#replace(where, *children) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/modular_tree/implementations.rb', line 194

def replace(where, *children)
  children = Array(children).flatten
  case where
    when Integer
      subject = @children[where] or raise ArgumentError
      index = where
    else
      subject = where
      index = @children.index(where) or raise ArgumentError
  end
  @children = @children[0...index] + children + @children[index + 1..-1]
  subject
end