Created
July 9, 2010 00:12
-
-
Save fauxparse/468835 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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