When a user registers for your app, you might want to add them to your mailing list. This normally takes a few seconds, as your app has to communicate with the mailing list provider. Still, the user should not have to wait, so we’ll immediately bring the user to the next page while subscribing them to the mailing list in the background.

This example uses MailChimp for the mailing list and Devise for authentication, but Active Job does not depend on either. The example uses gibbon gem to communicate with MailChimp, and dotenv to store the MailChimp API key and list ID as environment variables on dev.

First, add a job for adding a user to the mailing list.

1

bin/rails generate job subscribe_user_to_mailing_list

This generates a new job:

1

2

3

4

5

6

7

8

# app/jobs/subscribe_user_to_mailing_list.rb

classSubscribeUserToMailingListJob<ActiveJob::Base

queue_as:default

def perform(*args)

# Do something later

end

end

Next, customize the job to accept a user parameter, and subscribe that user to the MailChimp list.

Notice that we are passing the newly created user to the job, which then subscribes them to the mailing list.

Active Job is smart enough to realize that we don’t currently have a background job backend, so it performs the action right away, thus making the user wait. Once you add a backend, let Active Job know and you’ll have yourself a true background job. There are many backends to choose from, including Delayed Job, Sidekiq, and Resque,

Performing tasks in the background and eliminating delays for users has never been easier, thanks to Rails 4.2 and Active Job.