Created
May 14, 2009 21:01
-
-
Save jeremy/111919 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 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