This blog is part of our Rails 5 series.
Rails 4.2 came with built-in support for executing jobs in the background using Active Job. Along with many enhancements to Active Job, Rails 5 provides the ability to attach arbitrary metadata to any job.
Consider the scenario where we would like to get notified when a job has failed for more than three times. With the new enhancement, we can make it work by overriding serialize and deserialize methods of the job class.
1 2class DeliverWebhookJob < ActiveJob::Base 3 def serialize 4 super.merge('attempt_number' => (@attempt_number || 0) + 1) 5 end 6 7 def deserialize(job_data) 8 super(job_data) 9 @attempt_number = job_data['attempt_number'] 10 end 11 12 rescue_from(TimeoutError) do |ex| 13 notify_job_tried_x_times(@attempt_number) if @attempt_number == 3 14 retry_job(wait: 10) 15 end 16end 17
Earlier, deserialization was performed by #deserialize class method and therefore was inaccessible from the job instance. With the new changes, deserialization is delegated to the deserialize method on job instance thereby allowing it to attach arbitrary metadata when it gets serialized and read it back when it gets performed.