Skip to content

Commit

Permalink
Feature force_explicit_transactions!
Browse files Browse the repository at this point in the history
  • Loading branch information
antulik committed Jul 11, 2024
1 parent a1a5cb3 commit 5f9f37b
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions lib/active_interaction/extras/transaction.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,44 @@ module ActiveInteraction::Extras::Transaction

included do
class_attribute :run_in_transaction_options
set_callback :execute, :around, ->(_interaction, block) {

around_execute if: :run_in_transaction_options do |_interaction, block|
ActiveRecord::Base.transaction(**run_in_transaction_options) do
block.call
raise ActiveRecord::Rollback if _interaction.errors.any?
end
}, if: :run_in_transaction_options
end
end

class_methods do
# https://pragtob.wordpress.com/2017/12/12/surprises-with-nested-transactions-rollbacks-and-activerecord/
def run_in_transaction!(requires_new: true)
self.run_in_transaction_options = {requires_new: requires_new}
def run_in_transaction!(enabled = true, requires_new: true)
value =
if enabled
{ requires_new: requires_new }
else
false
end

self.run_in_transaction_options = value
end

def skip_run_in_transaction!
self.run_in_transaction_options = nil
self.run_in_transaction_options = false
end

def force_explicit_transactions!
before_filter do
if run_in_transaction_options.nil?
raise "Missing transaction definition. Add `run_in_transaction!`."
end
end
end

def list_missing_transaction_definition
Zeitwerk::Loader.eager_load_all
descendants
.select { |klass| klass.run_in_transaction_options.nil? }
end
end
end

0 comments on commit 5f9f37b

Please sign in to comment.