I wanted to get an object on production and do an exact replica( copy over its contents) to another object of same type. I tried doing this in 3 ways from ruby console which none of them worked:
Let's say you have the tt
as the first object you want to copy over and tt2
as the replica object. The first approach I tried is cloning the array
tt2.patients = tt.urls.patients
tt2.doctors = tt.segments.doctors
tt2.hospitals = tt.pixels.hospitals
Second approach I tried is duplicating the array which is actually the same as cloning the array:
tt2.patients = tt.patients.dup
tt2.doctors = tt.doctors.dup
tt2.hospitals = tt.hospitals.dup
Third approach I tried is marhsalling.
tt2.patients = Marshal.load(Marshal.dump(tt.patients))
tt2.doctors = Marshal.load(Marshal.dump(tt.doctors))
tt2.hospitals = Marshal.load(Marshal.dump(tt.hospitals))
None of the above works for deep copying from one array to another. After trying out each approach individually above, all the contents of the first object (tt
) are nullified (patients, doctors and hospitals are gone). Do you have any other ideas on copying the contents of one object to another? Thanks.
Ruby does provide two methods for making copies of objects, including one that can be made to do deep copies. The Object#dup method will make a shallow copy of an object. To achieve this, the dup method will call the initialize_copy method of that class.
A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.
It is a deep copy. It appears shallow in the case of Strings because under the covers, Strings are Singletons.
The #deep_dup method in Rails method returns true . This means that an instance that contains the Object class in its ancestor chain is eligible to deep copy.
Easy!
@new_tt = tt2.clone
@new_tt.patients = tt2.patients.dup
@new_tt.doctors = tt2.doctors.dup
@new_tt.hospitals = tt2.hospitals.dup
@new_tt.save
This is what ActiveRecord::Base#clone method is for:
@bar = @foo.clone
@bar.save
Ruby Facets is a set of useful extensions to Ruby and has a deep_clone method that might work for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With