I’ve got a method to ‘deep clone’ an object, basically to clone it
plus all of its associations.
Here is the code:
def deep_clone
clone = self.clone
%w[phone_numbers addresses websites emails].each do |assoc|
clone.send("#{assoc}=", self.send(assoc).collect { |obj|
obj.clone })
end
clone
end
This works perfectly in practice, the problem is that it is failing
during test, like so:
clone = orig.deep_clone
clone.save
clone.emails.size.should == orig.emails.size # This passes
orig.emails.each { |e| clone.email_ids.should_not include e.id } #
This fails
The fail is because the exact same email objects are assigned to both
the orig and the clone.
Looking at it in debug I can see that orig.emails and clone.emails (or
any other association for that matter) are tied together, such that
changing one mirrors the exact same change in the other.
I can also see that the clone is indeed a different object instance
from orig, it has a different id, and therefore clone.emails= should
not affect orig.emails.
Is this a bug or is there some nuance of the test environment I am
missing?
I am using the latest Rails 3 here, so I suspect it could be a genuine
bug…