How to use Active Job to decouple your background processing from a gem
With newer Rails you can also use ActiveJob as interface for a background processing library. See here for a list of supported queueing adapters.
For development and test it also brings its own queue adapters (async, inline and test). Note: For production use they don't recommend using these.
ActiveJob brings the advantage that the underlying background processing library can very easily be switched if there is the need to.
Code that all worker classes need can go to a
ApplicationJob class, similar to the use of
ApplicationRecord in Active Record (this is not enforced):
class ApplicationJob < ActiveJob::Base # common config goes here end
Regular Workers would then look like this (e.g.
class MyApiFetcherJob < ApplicationJob queue_as :default def perform(api_token, options) MyApiClient.new(api_token).fetch(options) end end
and could be called with
To define which queue adapter is used, set the config in your
application.rb (or e.g.
production.rb, if you prefer to have different adapters for different environments):
config.active_job.queue_adapter = :sidekiq
To set specific adapters in tests, you can create a
RSpec.configure do |config| config.before(:suite) do ActiveJob::Base.queue_adapter = :test end end
# Jobs should be worked off immediately in tests Rails.application.config.active_job.queue_adapter = :inline