---
title: "Attach arbitrary metadata to an Active Job in Rails 5"
description:
  "We can add arbitrary metadata to Active Job while it is serialized and read
  it back when the job is performed in Rails 5"
canonical_url: "https://www.bigbinary.com/blog/attach-arbitrary-metadata-to-an-active-job-in-rails-5"
markdown_url: "https://www.bigbinary.com/blog/attach-arbitrary-metadata-to-an-active-job-in-rails-5.md"
---

# Attach arbitrary metadata to an Active Job in Rails 5

We can add arbitrary metadata to Active Job while it is serialized and read it
back when the job is performed in Rails 5

- Author: Midhun Krishna
- Published: July 18, 2016
- Categories: Rails 5, Rails

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](https://github.com/rails/rails/pull/18260).

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.

```ruby

class DeliverWebhookJob < ActiveJob::Base
  def serialize
    super.merge('attempt_number' => (@attempt_number || 0) + 1)
  end

  def deserialize(job_data)
    super(job_data)
    @attempt_number = job_data['attempt_number']
  end

  rescue_from(TimeoutError) do |ex|
    notify_job_tried_x_times(@attempt_number) if @attempt_number == 3
    retry_job(wait: 10)
  end
end

```

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.

## Links

- [Human page](https://www.bigbinary.com/blog/attach-arbitrary-metadata-to-an-active-job-in-rails-5)
