Rails 5 adds another base class Application Job for jobs

Hitesh Rawal

Hitesh Rawal

June 12, 2016

This blog is part of our  Rails 5 series.

Rails 5 has added another base class ApplicationJob which inherits from ActiveJob::Base. Now by default all new Rails 5 applications will have application_job.rb.

1# app/jobs/application_job.rb
2class ApplicationJob < ActiveJob::Base
3end

In Rails 4.x if we want to use ActiveJob then first we need to generate a job and all the generated jobs directly inherit from ActiveJob::Base.

1# app/jobs/guests_cleanup_job.rb
2class GuestsCleanupJob < ActiveJob::Base
3  queue_as :default
4
5  def perform(*guests)
6    # Do something later
7  end
8end

Rails 5 adds explicit base class ApplicationJob for ActiveJob. As you can see this is not a big change but it is a good change in terms of being consistent with how controllers have ApplicationController and models have ApplicationRecord.

Now ApplicationJob will be a single place to apply all kind of customizations and extensions needed for an application, instead of applying patch on ActiveJob::Base.

Upgrading from Rails 4.x

When upgrading from Rails 4.x to Rails 5 we need to create application_job.rb file in app/jobs/ and add the following content.

1# app/jobs/application_job.rb
2class ApplicationJob < ActiveJob::Base
3end

We also need to change all the existing job classes to inherit from ApplicationJob instead of ActiveJob::Base.

Here is the revised code of GuestCleanupJob class.

1# app/jobs/guests_cleanup_job.rb
2class GuestsCleanupJob < ApplicationJob
3  queue_as :default
4
5  def perform(*guests)
6    # Do something later
7  end
8end

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.