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