Currently, I’m stuck in a situation where I’m changing values I’m not
intending to and I don’t know how to correct it.
I have… A class “Model” and a class “DataObject”. The “Data Object”
class has a method which takes in a “Model” and returns a new “Model”.
The problem is, my “generate_new_model” method is altering the input
“Model” object.
The below show basically what I’ve done to create the objects. Somehow
when I define a new “Model” for output and set it’s values to the source
model’s values, when I change the outputModel values it alters the
source model.
Am I right in guessing that you’re trying to put a copy of
modelSource into outputModel?
That’s exactly the case. In reading the link you suggest it seems I
would have to use a seperate data dumping operation. This seems a
little strange to me. Shouldn’t there be a more simple way to create a
copy of an object?
In reading the link you suggest it seems I
would have to use a seperate data dumping operation. This seems a
little strange to me. Shouldn’t there be a more simple way to
create a
copy of an object?
There’s no built-in method to create deep copies of any object,
though, and the serialise/unserialise thing just hacks around that in
the quickest way (as in, quickest to write).
If it were me, unless the Model class was extraordinarily
complicated, I’d probably just write my own copy method.
This isn’t perfect but:
class Object
def deeper_copy
copy = self.dup
self.instance_variables.each do |ivar|
copy.instance_variable_set(ivar,
self.instance_variable_get(ivar).dup)
end
copy
end
end
Note that this is specifically designed to work for regular style
classes (ie ones that store everything in instance variables) and
for Strings, Arrays and Structs its no better than (but no worse
than) #dup. Hence “deeper_copy” instead of “deep_copy”
There’s no built-in method to create deep copies of any object,
though, and the serialise/unserialise thing just hacks around that in
the quickest way (as in, quickest to write).
If it were me, unless the Model class was extraordinarily
complicated, I’d probably just write my own copy method.
You can as well override or reimplement the #dup method.
robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.