Skip to content

Instantly share code, notes, and snippets.

@Chris927
Created March 17, 2013 15:30
Show Gist options
  • Select an option

  • Save Chris927/5182041 to your computer and use it in GitHub Desktop.

Select an option

Save Chris927/5182041 to your computer and use it in GitHub Desktop.
Failed attempt to implement generic 'deep copy' for AR... I'm just keeping it to document the thought process and the dead end I've reached.
module CopyableAttributes
def self.included(base)
def copyable_attributes_keys2
attributes.keys - self.class.protected_attributes.to_a - [ "created_at", "updated_at"] - foreign_key_list
# TODO: we also need to remove foreign keys... maybe have class method 'uncopyable_attributes_keys'?
end
private
def relevant_base_class
baseclass = self.class
while baseclass.superclass != ActiveRecord::Base
baseclass = baseclass.superclass
end
baseclass
end
def foreign_key_list
baseclass = relevant_base_class
baseclass.foreign_key_list_recursive
end
def foreign_key_list_recursive
result = self.class.reflections.
select {|name, refl| refl.macro == :belongs_to }.
collect {|name, assoc| assoc.foreign_key }
result << self.class.descendants.collect {|d| d.copyable_attributes_keys2 }
# TODO: doesn't work, as 'copyable_attributes_keys2' is *not* a static method...
# we need ClassMethods to do this.
# TODO: There is an issue with sub classes being loaded only once required,
# class.descendants might therefore be incomplete (as least in dev mode):
# see http://stackoverflow.com/questions/5888313/ror-mymodel-descendants-returns-in-a-view-after-the-first-call
end
end
end
ActiveRecord::Base.send :include, CopyableAttributes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment