Skip to content

Instantly share code, notes, and snippets.

@MarioCarrion
Last active August 29, 2015 14:24
Show Gist options
  • Save MarioCarrion/68016cf68106ea60d608 to your computer and use it in GitHub Desktop.
Save MarioCarrion/68016cf68106ea60d608 to your computer and use it in GitHub Desktop.
Amoeba Deep Cloning Concern
# If you use amoeba (https://github.com/amoeba-rb/amoeba) for cloning your
# ActiveRecord objects this concern should be useful, it allows you properfly inherit
# associations if you use (Single Table) Inheritance.
#
# Just do something like:
#
# class SomeTable < ActiveRecord::Base
# has_many :somethings
#
# duplicate_this do
# include_association :somethings
# end
# end
module Duplicable
extend ActiveSupport::Concern
included do
class_attribute :amoeba_blocks
end
module ClassMethods
def inherited(subclass)
super
subclass.duplicate_this
end
def duplicate_this(&block)
self.amoeba_blocks ||= begin
blocks = [ Proc.new { enable } ]
superclass = nil
loop do
superclass = self.superclass
break if superclass == ActiveRecord::Base
blocks.unshift(*superclass.amoeba_blocks)
end
blocks << block if block_given?
blocks
end
blocks = self.amoeba_blocks
self.amoeba do |config|
blocks.each { |db| config.instance_eval(&db) }
end
end
end
def duplicate
blocks = self.class.amoeba_blocks || []
self.class.amoeba do |config|
blocks.each { |db| config.instance_eval(&db) }
end
self.amoeba_dup
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment