ruby-on-railscallbacksidekiqrails-activejobpaper-trail-gem

How to Implement `around_perform` callback after including Sidekiq (Sidekiq::Job) inside ApplicationJob


To streamline the inheritance of Sidekiq::Job into all of my jobs and as an attempt to leverage Rails' built-in callbacks, I've implemented ApplicationJob like this to log whodunnit data (I have also removed inheriting from ActiveJob::Base from ApplicationJob as it conflicts:

class ApplicationJob
  include Sidekiq::Job
  extend ActiveModel::Callbacks

  sidekiq_options queue: :default

  define_model_callbacks :perform

  around_perform :set_paper_trail_whodunnit

  def set_paper_trail_whodunnit
    PaperTrail.request.whodunnit = self.class.name
    yield
  ensure
    PaperTrail.request.whodunnit = nil
  end

  def perform(*args)
    run_callbacks(:perform) do
      perform!(*args)
    end
  end

  def perform!(*_args)
    raise NotImplementedError, 'Missing your #perform! method implementation'
  end
end

Now every job should inherit like this while also logging PaperTrail whodunnit:

class ExampleJob < ApplicationJob
  def perform(record_id)
    Record.find(record_id).update!(column: new_value)
  end
end

However what ends up happening is that the around_perform callback is never reached, never fires, and as a result, whodunnit is never properly set.

I've attempted to manually inherit around_perform in ApplicationJob through:

extend ActiveJob::Callbacks

or through:

extend ActiveJob::Callbacks::ClassMethods

But this never fires either. Or is reached when I include a breakpoint inside set_paper_trail_whodunnit


Solution

  • Thanks to Maxence who gave me the lead.

    perform in the Worker, or individual Job as it is referred to in Sidekiq documentation, was indeed being overwritten by any Job that was inheriting ApplicationJob thereby meaning that the around_perform callback was never being triggered.

    I've gone inside my Worker files and changed there methods from perform to perform! so that these callbacks can be run.