after_commit_queue.rb 1.37 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7 8 9 10
module AfterCommitQueue
  extend ActiveSupport::Concern

  included do
    after_commit :_run_after_commit_queue
    after_rollback :_clear_after_commit_queue
  end

11
  def run_after_commit(&block)
12
    _after_commit_queue << block if block
13 14 15 16 17 18

    true
  end

  def run_after_commit_or_now(&block)
    if AfterCommitQueue.inside_transaction?
19 20 21 22 23 24 25 26 27
      if ActiveRecord::Base.connection.current_transaction.records.include?(self)
        run_after_commit(&block)
      else
        # If the current transaction does not include this record, we can run
        # the block now, even if it queues a Sidekiq job.
        Sidekiq::Worker.skipping_transaction_check do
          instance_eval(&block)
        end
      end
28 29 30 31
    else
      instance_eval(&block)
    end

32 33 34
    true
  end

35 36 37 38 39 40 41 42 43 44 45 46
  def self.open_transactions_baseline
    if ::Rails.env.test?
      return DatabaseCleaner.connections.count { |conn| conn.strategy.is_a?(DatabaseCleaner::ActiveRecord::Transaction) }
    end

    0
  end

  def self.inside_transaction?
    ActiveRecord::Base.connection.open_transactions > open_transactions_baseline
  end

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
  protected

  def _run_after_commit_queue
    while action = _after_commit_queue.pop
      self.instance_eval(&action)
    end
  end

  def _after_commit_queue
    @after_commit_queue ||= []
  end

  def _clear_after_commit_queue
    _after_commit_queue.clear
  end
end