ActiveRecord object cloning

65 views
Skip to first unread message

Paul Gillard

unread,
Aug 13, 2009, 3:58:58 PM8/13/09
to Ruby on Rails: Core
In Ruby when an object is cloned the newly created object is
initialized via #initialize_copy. Only new objects are initialized via
#initialize.

Currently ActiveRecord::Base overrides #clone and creates clones using
#new. This means newly cloned objects are initialized via a
combination of #clone and #initialize instead of via #initialize_copy.
Is the Rails core group interested in seeing a patch which removes the
ActiveRecord#clone method and instead implements cloning by defining
an #initialize_copy method?

Doing so would make implementing application specific deep cloning
much easier as classes can simply define their own #initialize_copy
method.

Joshua Peek

unread,
Aug 13, 2009, 4:39:06 PM8/13/09
to rubyonra...@googlegroups.com
+1, overriding initialize_copy is the correct way. We shouldn't be
overriding dup and clone.
--
Joshua Peek

Mark Turner

unread,
Aug 13, 2009, 5:13:58 PM8/13/09
to rubyonra...@googlegroups.com
On Thu, Aug 13, 2009 at 12:58 PM, Paul
Gillard<paulmg...@googlemail.com> wrote:
> Currently ActiveRecord::Base overrides #clone and creates clones using
> #new. This means newly cloned objects are initialized via a
> combination of #clone and #initialize instead of via #initialize_copy.
> Is the Rails core group interested in seeing a patch which removes the
> ActiveRecord#clone method and instead implements cloning by defining
> an #initialize_copy method?


Wasn't some of the stuff is AR::Base#clone fixed to handle issues with
attribute copying or initializers? I think I remember something like 3
years ago.. but I'm too lazy to search.

My feeling is that AR::Base#clone does was 99% of developers expect it
to do. Any deep copying that happens usually ends up in a unique
method on the class a la 'object.deep_copy'. I support the idea of
the change, I just worry that it might be more work than its worth.

Paul Gillard

unread,
Oct 6, 2009, 1:25:54 PM10/6/09
to Ruby on Rails: Core
I've created a patch for this change which can be found at
https://rails.lighthouseapp.com/projects/8994/tickets/3164. All the
tests pass and #clone acts correctly. However I'd really appreciate
some feedback on one niggling point regarding when the
after_initialize callbacks get run.
Reply all
Reply to author
Forward
0 new messages