Created
January 27, 2011 19:11
-
-
Save ckdake/799014 to your computer and use it in GitHub Desktop.
monkey patch to Ancestry to add tree cloning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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