Created
October 3, 2008 15:23
-
-
Save bguthrie/14571 to your computer and use it in GitHub Desktop.
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 ActiveRecord | |
class KindRollback < Rollback | |
end | |
end | |
module UpdateAttributesWithKind | |
def self.included(model_class) | |
model_class.alias_method_chain :update_attributes, :kind | |
end | |
def update_attributes_with_kind(attributes={}) | |
if attributes.has_key?(:kind) | |
switch_kind(attributes[:kind]) do |new_self| | |
new_self.update_attributes_without_kind attributes.except(:kind) | |
raise ActiveRecord::KindRollback unless new_self.valid? | |
end | |
else | |
update_attributes_without_kind attributes | |
end | |
end | |
def switch_kind(kind_name) | |
return self if kind_name == self.kind | |
old_kind = self.kind | |
self.kind = kind_name | |
self.save_without_validation | |
returning(kind_name.constantize.find(self.id)) { |new_self| yield new_self if block_given? } | |
rescue ActiveRecord::KindRollback | |
self.kind = old_kind | |
self.save_without_validation | |
self | |
rescue Exception | |
self.kind = old_kind | |
self.save_without_validation | |
raise | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment