Skip to content

Instantly share code, notes, and snippets.

@sbellware
Created May 31, 2010 01:39
Show Gist options
  • Save sbellware/419461 to your computer and use it in GitHub Desktop.
Save sbellware/419461 to your computer and use it in GitHub Desktop.
Copy ActiveRecord model values to another model
module Copyable
attr_writer :copyable_attributes
def copyable_attributes
@copyable_attributes ||= attributes.keys.reject { |k, v| k.to_s =~ /^id$|_id$|^created_at$|^updated_at$/ }
end
def copy(options={})
class_sym = options.delete :class
other = options.delete :other
if not other
if class_sym
other_class = Kernel.const_get class_sym.to_s.classify
else
other_class = self.class
end
other = other_class.new
end
copyable_attributes.each do |k|
other.write_attribute k, attributes[k]
end
other
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment