Skip to content

Instantly share code, notes, and snippets.

@albertosaurus
Last active November 22, 2021 17:12
Show Gist options
  • Save albertosaurus/19c523b8b182e8702ebe73bf6f1a0e97 to your computer and use it in GitHub Desktop.
Save albertosaurus/19c523b8b182e8702ebe73bf6f1a0e97 to your computer and use it in GitHub Desktop.
Rails programming trick - macro to wrap a method call in a transaction
module WithTransaction
extend ActiveSupport::Concern
module ClassMethods
# Wrap the given method in a transaction.
def with_transaction(method_name)
define_method "#{method_name}_with_transaction" do |*args, &block|
::ActiveRecord::Base.transaction do
self.__send__("#{method_name}_without_transaction", *args, &block)
end
end
alias_method_chain method_name, :transaction
end
end
end
# You can now do things like...
class Foo
include WithTransaction
with_transaction def bar(arg1, arg2)
# Everything in this method is now wrapped in a db transaction
arg1.some_operation
arg2.some_other_operation
arg1.save!
arg2.save!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment