Method: FishTransactions::Callbacks#after_transaction
- Defined in:
- lib/fish_transactions/callbacks.rb
#after_transaction(opts = {}, &block) ⇒ Object Also known as: after_tx
Allows to execute any block of code after transaction completes. If no transaction is actually open, the code runs immediately.
Accepts the following options that modifies this behavior:
-
:only
- Execute this code only on commit or only on rollback. Accepts one of the following symbols::commit
,:rollback
. -
:if_no_transaction
- Specifies what to do if there is no active transaction. Accepts one of the following symbols::run
(default),:skip
(do not run).
Example of use:
ActiveRecord::Base.transaction do
# executes some code
puts "runs within transaction"
after_transaction do
# things to do after transaction
puts "runs after transaction"
end
# executes more code
puts "again runs within transaction"
end
will output
runs within transaction
again runs within transaction
runs after transaction
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/fish_transactions/callbacks.rb', line 88 def after_transaction(opts = {}, &block) # default options = { only: nil, if_no_transaction: :run} opts = .merge(opts) # normalize opts to string keys normalized = opts.dup opts.each{ |k,v| normalized[k.to_s] = v } opts = normalized if ActiveRecord::Base.connection.open_transactions > 0 callbacks = ActiveRecord::Base.callbacks case opts['only'] when :commit callbacks.store(:commit,&block) when :rollback callbacks.store(:rollback,&block) else # both cases callbacks.store(:commit,&block) callbacks.store(:rollback,&block) end else if opts['if_no_transaction'] == :run block.call end end end |