Posted 4 months ago. Visible to the public. Repeats.

How to use Active Job to decouple your background processing from a gem

In a web application you sometimes have tasks that can not be processed during a request but need to go to the background.
There are several gems that help to you do that, like Sidekiq or Resque.

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.

Using 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. app/jobs/my_api_fetcher_job.rb):

class MyApiFetcherJob < ApplicationJob queue_as :default def perform(api_token, options) end end

and could be called with MyApiFetcherJob.perform_later('super-secret', options).

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 spec/support/active_job.rb with:

RSpec.configure do |config| config.before(:suite) do ActiveJob::Base.queue_adapter = :test end end

and a features/support/active_job.rb with:

# Jobs should be worked off immediately in tests Rails.application.config.active_job.queue_adapter = :inline

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Judith Roth
Last edit:
4 months ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Judith Roth to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more