Skip to content

Instantly share code, notes, and snippets.

@ckdake
Created January 27, 2011 19:11
Show Gist options
  • Save ckdake/799014 to your computer and use it in GitHub Desktop.
Save ckdake/799014 to your computer and use it in GitHub Desktop.
monkey patch to Ancestry to add tree cloning
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment