Skip to content

Instantly share code, notes, and snippets.

@fauxparse
Created July 9, 2010 00:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fauxparse/468835 to your computer and use it in GitHub Desktop.
Save fauxparse/468835 to your computer and use it in GitHub Desktop.
module Mongoid
module DeepCloning
def deep_clone(attrs = {}, obj = nil)
returning obj || self.class.new do |o|
o.write_attributes(@attributes.merge(attrs).except("_id", "versions").except(*o.class.associations.keys))
yield o if block_given?
o.save
@attributes.each_pair do |key, value|
next unless proxy = self.associations[key]
case proxy.association
when Mongoid::Associations::EmbedsMany
value.each do |v|
v.deep_clone({}, o.send(key).build)
end
when Mongoid::Associations::EmbedsOne
value.deep_clone({}, o.send(:"build_#{key}"))
else
o.send :"#{key}=", value
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment