module ActiveRecord::Transactions

def self.included(base)

def self.included(base)
  base.extend(ClassMethods)
  base.class_eval do
    [:destroy, :save, :save!].each do |method|
      alias_method_chain method, :transactions
    end
  end
end

def destroy_with_transactions #:nodoc:

:nodoc:
def destroy_with_transactions #:nodoc:
  with_transaction_returning_status(:destroy_without_transactions)
end

def rollback_active_record_state!

Reset id and @new_record if the transaction rolls back.
def rollback_active_record_state!
  id_present = has_attribute?(self.class.primary_key)
  previous_id = id
  previous_new_record = new_record?
  yield
rescue Exception
  @new_record = previous_new_record
  if id_present
    self.id = previous_id
  else
    @attributes.delete(self.class.primary_key)
    @attributes_cache.delete(self.class.primary_key)
  end
  raise
end

def save_with_transactions(perform_validation = true) #:nodoc:

:nodoc:
def save_with_transactions(perform_validation = true) #:nodoc:
  rollback_active_record_state! { with_transaction_returning_status(:save_without_transactions, perform_validation) }
end

def save_with_transactions! #:nodoc:

:nodoc:
def save_with_transactions! #:nodoc:
  rollback_active_record_state! { self.class.transaction { save_without_transactions! } }
end

def transaction(&block)

See ActiveRecord::Transactions::ClassMethods for detailed documentation.
def transaction(&block)
  self.class.transaction(&block)
end

def with_transaction_returning_status(method, *args)

instance.
This method is available within the context of an ActiveRecord::Base

a ROLLBACK is issued. In any case the status flag is returned.
status flag. If the status is true the transaction is committed, otherwise
Executes +method+ within a transaction and captures its return value as a
def with_transaction_returning_status(method, *args)
  status = nil
  self.class.transaction do
    status = send(method, *args)
    raise ActiveRecord::Rollback unless status
  end
  status
end