From 5f9f37b52ab1ac716c7c901dfc97ca2444646224 Mon Sep 17 00:00:00 2001 From: Anton Katunin Date: Thu, 11 Jul 2024 17:35:26 +1000 Subject: [PATCH] Feature force_explicit_transactions! --- lib/active_interaction/extras/transaction.rb | 32 +++++++++++++++++--- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/lib/active_interaction/extras/transaction.rb b/lib/active_interaction/extras/transaction.rb index 76eac10..fed243d 100644 --- a/lib/active_interaction/extras/transaction.rb +++ b/lib/active_interaction/extras/transaction.rb @@ -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