Skip to content

Instantly share code, notes, and snippets.

@bguthrie
Created October 3, 2008 15:23
Show Gist options
  • Save bguthrie/14571 to your computer and use it in GitHub Desktop.
Save bguthrie/14571 to your computer and use it in GitHub Desktop.
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