Skip to content

Instantly share code, notes, and snippets.

@jeremy
Created May 14, 2009 21:01
Show Gist options
  • Save jeremy/111919 to your computer and use it in GitHub Desktop.
Save jeremy/111919 to your computer and use it in GitHub Desktop.
module AfterTransaction
def self.included(base)
base.extend(ClassMethods)
base.class_eval do
class <<self
alias_method_chain :transaction, :callbacks
end
end
end
module ClassMethods
@@after_transaction_hooks = []
def transaction_with_callbacks(&block)
clean = true
transaction_without_callbacks(&block)
rescue Exception
clean = false
raise
ensure
if connection.open_transactions.zero?
after_transaction_callbacks if clean
clear_transaction_callbacks!
end
end
def after_transaction(&block)
if connection.open_transactions.zero?
yield
else
@@after_transaction_hooks << block
end
end
private
def after_transaction_callbacks
@@after_transaction_hooks.each { |hook| hook.call }
end
def clear_transaction_callbacks!
@@after_transaction_hooks.clear
end
end
def after_transaction(&block)
self.class.after_transaction(&block)
end
end
ActiveRecord::Base.send(:include, AfterTransaction)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment