This post is part of a series of 31 Rails 4 articles being released each day in December 2012.
It doesn't matter what the size of your Rails application is, you probably have reached a point where you had to add support for a queue to run background jobs. At that point you're left to choose between different options, and of course, each option has its own flavour.
Rails 4 decided to solve that issue by unifying the queueing interface, and allowing you to create your own queue or use any queue engine that complies with the interface.
The new interface is pretty simple. The
ActiveSupport::Queue class comes with a
push method that accepts any object, as long as that object defines a
Let's say that you have a job class
PrintName that prints the name of an author.
class PrintName def initialize(author) @author = author end def run puts @author.name end end
You can queue a job to print the name in the background by pushing an instance of that class to
That's basically it, the print job will run in a background thread and it will not block any of your operations.
If you're using your own queue, make sure you update your interface to comply with Rails and update your application configuration accordingly. To set a queue, in
config.queue = MyQueue.new
If you're using a 3rd party alternative, keep an eye out for updates. Personally, I use Sidekiq, which already has a Rails 4 ready branch. In case of Sidekiq, you don't need to configure your default queue, as Sidekiq does this for you.
This post is by Rida Al Barazi. Rida is a passionate web developer experienced in building web applications for startups. He started working with Rails in 2005, co-authored Beginning Rails 3, and has spoken at conferences around the world.