Class: Mongoid::Acts::Tree::Children

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

Overview

proxy class

Instance Method Summary collapse

Constructor Details

#initialize(owner) ⇒ Children

TODO: improve accessors to options to eliminate object



190
191
192
193
# File 'lib/mongoid_acts_as_tree.rb', line 190

def initialize(owner)
  @parent = owner
  self.concat find_children_for_owner.to_a
end

Instance Method Details

#<<(object, will_save = true) ⇒ Object Also known as: push

Add new child to list of object children



196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/mongoid_acts_as_tree.rb', line 196

def <<(object, will_save=true)
  if object.descendants.include? @parent
    object.instance_variable_set :@_cyclic, true
  else
    object.write_attribute object.parent_id_field, @parent._id
    object[object.path_field] = @parent[@parent.path_field] + [@parent._id]
    object[object.depth_field] = @parent[@parent.depth_field] + 1
    object.instance_variable_set :@_will_move, true
    object.save if will_save
  end

  super(object)
end

#build(attributes) ⇒ Object Also known as: create



210
211
212
213
214
# File 'lib/mongoid_acts_as_tree.rb', line 210

def build(attributes)
  child = @parent.class.new(attributes)
  self.push child
  child
end

#clearObject

Clear children list



239
240
241
242
243
# File 'lib/mongoid_acts_as_tree.rb', line 239

def clear
  self.each do | child |
    @parent.children.delete child
  end
end

#delete(object_or_id) ⇒ Object

Deletes object only from children list. To delete object use object.destroy.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/mongoid_acts_as_tree.rb', line 222

def delete(object_or_id)
  object = case object_or_id
    when String, BSON::ObjectId
      @parent.class.find object_or_id
    else
      object_or_id
  end

  object.write_attribute object.parent_id_field, nil
  object[object.path_field]      = []
  object[object.depth_field]     = 0
  object.save

  super(object)
end