Created
May 31, 2010 01:39
-
-
Save sbellware/419461 to your computer and use it in GitHub Desktop.
Copy ActiveRecord model values to another model
This file contains hidden or 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 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