Module: TrxExt::ObjectExt

Defined in:
lib/trx_ext/object_ext.rb

Instance Method Summary collapse

Instance Method Details

#trxObject

A shorthand version of ActiveRecord::Base.transaction



42
43
44
45
46
47
48
# File 'lib/trx_ext/object_ext.rb', line 42

def trx(...)
  # If trx method is called over AR model - we should take this into account. Otherwise - call it over
  # ActiveRecord::Base class. This ensures proper connection picking in sharded environment.
  return transaction(...) if respond_to?(:transaction)

  ActiveRecord::Base.transaction(...)
end

#wrap_in_trx(method, class_name = nil) ⇒ Symbol

Wraps specified method in an ActiveRecord transaction.

Examples:

class User < ActiveRecord::Base
  class << self
    wrap_in_trx def find_or_create(name)
      user = find_by(name: name)
      user ||= create(name: name, title: 'Default')
      user
    end
  end
end

User.find_or_create('some name')
#   (0.6ms)  BEGIN
#   User Load (0.4ms)  SELECT "users".* FROM "users" WHERE "users"."name" = $1 LIMIT 1  [["name", 'some name']]
#   User Create (1.8 ms) INSERT INTO "users" ("name", "title") VALUES ($1, $2) RETURNING "id"  [["name", "some name"], ["title", "Default"]]
#   (0.2ms)  COMMIT

Parameters:

  • method (Symbol)

    a name of the method

  • class_name (String, nil) (defaults to: nil)

    pass an ActiveRecord model class name to define the appropriate connection of the transaction

Returns:

  • (Symbol)


28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/trx_ext/object_ext.rb', line 28

def wrap_in_trx(method, class_name = nil)
  module_to_prepend = Module.new do
    define_method(method) do |*args, **kwargs, &blk|
      context = class_name&.constantize || self
      context.trx do
        super(*args, **kwargs, &blk)
      end
    end
  end
  prepend module_to_prepend
  method
end