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
.
# app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base
end
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
.
# app/jobs/guests_cleanup_job.rb
class GuestsCleanupJob < ActiveJob::Base
queue_as :default
def perform(*guests)
# Do something later
end
end
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
.
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.
# app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base
end
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.
# app/jobs/guests_cleanup_job.rb
class GuestsCleanupJob < ApplicationJob
queue_as :default
def perform(*guests)
# Do something later
end
end
If this blog was helpful, check out our full blog archive.