Sha256: 768a7ef5b81058bece49375f16d25008375493fba602a835f9d31c3b9d9dd970

Contents?: true

Size: 1.48 KB

Versions: 13

Compression:

Stored size: 1.48 KB

Contents

require 'active_support/concern'

module RocketJob
  module Plugins
    # Wraps every #perform call with an Active Record transaction / unit or work.
    #
    # If the perform raises an exception it will cause any database changes to be rolled back.
    #
    # For Batch Jobs the transaction is at the slice level so that the entire slice succeeds,
    # or is rolled back.
    #
    # Example:
    #   # Update User and create an Audit entry as a single database transaction.
    #   # If Audit.create! fails then the user change will also be rolled back.
    #   class MyJob < RocketJob::Job
    #     include RocketJob::Plugins::Transaction
    #
    #     def perform
    #       u = User.find(name: 'Jack')
    #       u.age = 21
    #       u.save!
    #
    #       Audit.create!(table: 'user', description: 'Changed age to 21')
    #     end
    #   end
    #
    # Performance
    # - On CRuby an empty transaction block call takes about 1ms.
    # - On JRuby an empty transaction block call takes about 55ms.
    #
    # Note:
    # - This plugin will only be activated if ActiveRecord has been loaded first.
    module Transaction
      extend ActiveSupport::Concern

      included do
        if defined?(ActiveRecord::Base)
          respond_to?(:around_slice) ? around_slice(:rocket_job_transaction) : around_perform(:rocket_job_transaction)
        end
      end

      private

      def rocket_job_transaction(&block)
        ActiveRecord::Base.transaction(&block)
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rocketjob-5.1.1 lib/rocket_job/plugins/transaction.rb
rocketjob-5.1.0 lib/rocket_job/plugins/transaction.rb
rocketjob-5.0.0 lib/rocket_job/plugins/transaction.rb
rocketjob-5.0.0.rc1 lib/rocket_job/plugins/transaction.rb
rocketjob-5.0.0.beta4 lib/rocket_job/plugins/transaction.rb
rocketjob-5.0.0.beta3 lib/rocket_job/plugins/transaction.rb
rocketjob-5.0.0.beta2 lib/rocket_job/plugins/transaction.rb
rocketjob-5.0.0.beta lib/rocket_job/plugins/transaction.rb
rocketjob-4.3.0.beta2 lib/rocket_job/plugins/transaction.rb
rocketjob-4.3.0.beta lib/rocket_job/plugins/transaction.rb
rocketjob-4.2.0 lib/rocket_job/plugins/transaction.rb
rocketjob-4.1.1 lib/rocket_job/plugins/transaction.rb
rocketjob-4.1.0 lib/rocket_job/plugins/transaction.rb