Use ActiveJob in Rails 4.1
ActiveJob is the headline feature in Rails 4.2, the Active Job Basics on RailsGuides explains the philosophy and usage very well, make sure you’ve checked that first. However there’re some gotchas if you want to use it right now in your Rails 4.1 app. Here I’m gonna show you how to install it in 4.1, and things you need to take extra care of.
Install ActiveJob in Rails 4.1
activejob to your
active_job.rb file under
config/initializers and paste code below.
require 'active_job' # or any other supported backend such as :sidekiq or :delayed_job ActiveJob::Base.queue_adapter = :inline
Now you should be abel to load ActiveJob in your rails app without error.
Note that the one you installed is not the one inside the rails repository, that has a version of 4.2.0.beta2 same as Rails at the time of writing, the one you installed is version 0. You can find the archived source code from its original repository.
Creating a Job
To create a job, you have to manually create the
app/jobs folder first, then follow the same naming convention to create your job class file like
class GuestsCleanupJob < ActiveJob::Base queue_as :default def perform(*args) # Do something later end end
Enqueuing the Job
GuestsCleanupJob.enqueue(record) GuestsCleanupJob.enqueue(record, options)
Differences between latest ActiveJob
- no rails generator for jobs.
- no callback mechanism like
- doesn’t load itself to rails app by default, that’s why you need a initializer to load it manually.
- enqueue syntax is slightly different, in Rails 4.2.beta2
enqueuehas changed to
- internally it’s using activemodel-globalid instead of GlobalID(GlobalID is renamed from activemodel-globalid).
- setting backend syntax is slightly different
# Rails 4.2.beta2 Rails.application.config.active_job.queue_adapter = :delayed_job # Rails 4.1 ActiveJob::Base.queue_adapter = :delayed_job
p.s. I haven’t checked ActionMailer. I’m currently using it with DelayedJob and so far so good.
ActiveJob is very convenient, it provides a unified interface for the job infrastructure that allows you to switch the backend easily.
But as you can see there’re big diffs between the latest developed version and the one now we’re able to install in Rails 4.1.
Is it worth it to make the effort to try it now, and push these small upcoming changes when you upgrade to Rails 4.2 to your mental stack? My suggestion is if you’re just right about to implement a queue system and willing to adapt to it, then it’s OK, otherwise maybe better just leave the current app running as is and wait for a more mature timing.