ruby-on-railssidekiqpaper-trail-gem

How set paper trail whodunnit for workers using sidekiq


I am trying to implement that when inside a worker a model that has paper trail is updated the whodunnit must be set with 'worker', I tried many things without success, the last one was to try a solution found in a github thread the problem is that I have workers with perfom without / with 1 or multiple params( I changed this to set PaperTrail.request.whodunnit = 'worker')

How can I set whodunnit before or around each perform, so that the whodunnit in the versions is saved as whodunnit: worker?

my workers look like this:

module ModuleName
  module Workers
    class WorkerClass
      include Sidekiq::Worker

      sidekiq_options queue: 'default', retry: true


      def perform # here with none, 1 or more params
        # update some model
      end
    end
  end
end


Solution

  • The solution for me

    base_worker.rb

    class BaseWorker
      extend ActiveModel::Callbacks
      define_model_callbacks :perform
    
      around_perform :set_paper_trail_whodunnit
    
      def set_paper_trail_whodunnit
        PaperTrail.request.whodunnit = "worker-#{self.class.name}"
        yield
        PaperTrail.request.whodunnit = nil
      end
    
      def perform(*args)
        run_callbacks(:perform) do
          perform!(*args)
        end
      end
    
      def perform!(*_args)
        raise 'Missing your #perform! method implementation'
      end
    end
    

    workers:

    module ModuleName
      module Workers
        class WorkerClass < ::BaseWorker
          include Sidekiq::Worker
    
          sidekiq_options queue: 'default', retry: true
    
    
          def perform! # here with none, 1 or more params
            # update some model
          end
        end
      end
    end