Module: ActiveRecord::Base::DeepCloneable
- Included in:
- ActiveRecord::Base
- Defined in:
- lib/deep_cloneable.rb
Defined Under Namespace
Classes: AssociationNotFoundException
Instance Method Summary collapse
-
#dup(*args, &block) ⇒ Object
Deep dups an ActiveRecord model.
Instance Method Details
#dup(*args, &block) ⇒ Object
Deep dups an ActiveRecord model. See README.rdoc
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/deep_cloneable.rb', line 20 def dup *args, &block = args[0] || {} dict = [:dictionary] dict ||= {} if .delete(:use_dictionary) kopy = unless dict super() else tableized_class = self.class.name.tableize.to_sym dict[tableized_class] ||= {} dict[tableized_class][self] ||= super() end block.call(self, kopy) if block deep_exceptions = {} if [:except] exceptions = [:except].nil? ? [] : [[:except]].flatten exceptions.each do |attribute| kopy.send(:write_attribute, attribute, self.class.column_defaults.dup[attribute.to_s]) unless attribute.kind_of?(Hash) end deep_exceptions = exceptions.select{|e| e.kind_of?(Hash) }.inject({}){|m,h| m.merge(h) } end if [:include] Array([:include]).each do |association, deep_associations| if (association.kind_of? Hash) deep_associations = association[association.keys.first] association = association.keys.first end = deep_associations.blank? ? {} : {:include => deep_associations} .merge!(:except => deep_exceptions[association]) if deep_exceptions[association] .merge!(:dictionary => dict) if dict association_reflection = self.class.reflect_on_association(association) raise AssociationNotFoundException.new("#{self.class}##{association}") if association_reflection.nil? if [:validate] == false kopy.instance_eval do # Force :validate => false on all saves. def perform_validations(={}) [:validate] = false super() end end end cloned_object = send( "dup_#{association_reflection.macro}_#{association_reflection.class.name.demodulize.underscore.gsub('_reflection', '')}", { :reflection => association_reflection, :association => association, :copy => kopy, :dup_options => }, &block ) kopy.send("#{association}=", cloned_object) end end return kopy end |