public
Last active

monkey patch to Ancestry to add tree cloning

  • Download Gist
clone_with_modifications.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
module Ancestry
# https://github.com/stefankroes/ancestry
module InstanceMethods
# Clone an object and all children
# => replacing values with those from attributes if present
# => setting parent to new parent if present
# => setting the "original_id_field_name" if present to the id of the original object
#
# Example use_case:
#
# class Category < ActiveRecord::Base
# belongs_to :project
# belongs_to :source_category, :class_name => "Category"
# scope :defaults, where(:project_id => nil)
# def self.import_from_defaults_for(project)
# defaults.roots.all.each do |root|
# root.clone_with_modifications!({:project_id => project.id}, nil, :source_category_id)
# end
# end
#
# class Project < ActiveRecord::Base
# has_many :categories, :dependent => :destroy
# after_create Proc.new { |p| Category.import_from_defaults_for(self) }
# end
#
def clone_with_modifications!(attributes = nil, parent = nil, original_id_field_name = nil)
clone = self.class.create!(self.attributes.merge(:ancestry => nil).merge(attributes))
clone.send("#{original_id_field_name}=", self.id) if original_id_field_name
clone.parent = parent
self.children.each { |child| child.clone_with_modifications!(attributes, clone, original_id_field_name) }
clone.save!
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.