Home > Software engineering >  How to avoid code duplication in Rails Sidekiq schedule job and worker with the same code
How to avoid code duplication in Rails Sidekiq schedule job and worker with the same code

Time:06-09

I've got Sidekiq worker SyncProductsWorker which calls inside the controller action:

class ProductsController < BaseApiController
  def fetch_all
    ::Imports::FetchAllProductsWorker.perform_async

    head :ok
  end
end

And Sidekiq job FetchAllProductsJob with the same code as SyncProductsWorker as a schedule job inside sidekiq.yml

sidekiq.yml

:queues:
  - imports_fetch_all
:dynamic: true
:schedule:
  imports_fetch_all_job:
    cron: '0 0 * * *' # at midnight
    class: Imports::FetchAllProductsJob
    queue: imports_fetch_all

So basically both classes, worker and job looks almost the same:

# worker
module Imports
  class FetchAllProductsWorker
    include Sidekiq::Worker
    sidekiq_options queue: 'imports_fetch_all'

    def perform
      puts 'test'
    end
  end
end

# schedule job
module Imports
  class FetchAllProductsJob < ApplicationJob
    sidekiq_options queue: 'imports_fetch_all'

    def perform
      puts 'test'
    end
  end
end

How to avoid code duplication to not have two files with the same code?

CodePudding user response:

There is no reason to talk to Sidekiq directly in one place, and ActiveJob in another place. Both places can just talk directly to the ActiveJob job. Delete your Sidekiq worker, and replace your call to the worker's perform_async with a call to the job's perform_later:

  def fetch_all
    ::Imports::FetchAllProductsJob.perform_later

    head :ok
  end
  • Related