Module: Mongoid::Copyable

Extended by:
ActiveSupport::Concern
Included in:
Composable
Defined in:
build/mongoid-7.3/lib/mongoid/copyable.rb

Overview

This module contains the behavior of Mongoid’s clone/dup of documents.

Instance Method Summary collapse

Instance Method Details

#cloneDocument Also known as: dup

Clone or dup the current Document. This will return all attributes with the exception of the document’s id, and will reset all the instance variables.

This clone also includes embedded documents.

Examples:

Clone the document.

document.clone

Returns:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'build/mongoid-7.3/lib/mongoid/copyable.rb', line 20

def clone
  # @note This next line is here to address #2704, even though having an
  # _id and id field in the document would cause problems with Mongoid
  # elsewhere.
  attrs = clone_document.except(*self.class.id_fields)
  dynamic_attrs = {}
  _attribute_names = self.attribute_names
  attrs.reject! do |attr_name, value|
    unless _attribute_names.include?(attr_name)
      dynamic_attrs[attr_name] = value
      true
    end
  end
  self.class.new(attrs).tap do |object|
    dynamic_attrs.each do |attr_name, value|
      if object.respond_to?("#{attr_name}=")
        object.send("#{attr_name}=", value)
      else
        object.attributes[attr_name] = value
      end
    end
  end
end