moiristo / deep_cloneable

This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations.
MIT License
785 stars 89 forks source link

Question: How to deep clone classes associated to the same class, as in a linked list or tree? #129

Closed jim0020 closed 3 years ago

jim0020 commented 3 years ago

Say I have a TreeNode class: class TreeNode < ApplicationRecord has_many :children, class: :TreeNode, foreign_key: :parent, inverse_of: :parent belongs_to :parent, class: :TreeNode, inverse_of: :children end

how would you deep_clone a given TreeNode object to deep clone the object and all the children, the children's children, etc?

moiristo commented 3 years ago

I don't think deep_cloneable would be very useful in your case. I would make a recursive method and use dup directly instead. Something like this:

class TreeNode < ApplicationRecord
  def duplicate
    dup.tap { |node| node.children = children.map(&:duplicate) }
  end
end