In Rails 8.1, how do you let an Active Job accept a custom value object as an argument, and what must its serializer implement?
answer
- unsupported type fails at enqueue
- subclass ObjectSerializer
- serialize, deserialize, public klass
- config.active_job.custom_serializers
- autoload_once_paths, not reloadable
basics
~10 sWrite a subclass of ActiveJob::Serializers::ObjectSerializer with serialize, deserialize and a public klass method, then register it through config.active_job.custom_serializers. Without one, perform_later raises ActiveJob::SerializationError for the unsupported type.
solid answer
~40 sActive Job serializes a fixed set of types (primitives, `Symbol`, `BigDecimal`, dates and times, `Duration`, `Range`, `Module`, arrays and hashes with string or symbol keys) plus anything with a GlobalID; anything else raises `ActiveJob::SerializationError` ("Unsupported argument type") in the caller. For a value object such as a `CertificateGrade`, subclass `ActiveJob::Serializers::ObjectSerializer`: `serialize(grade)` calls `super` with a string-keyed hash of JSON-safe values, which adds an `_aj_serialized` key naming the serializer; `deserialize(hash)` rebuilds the object; and a **public** `klass` returns the class it handles so Active Job can index it. Register it with `Rails.application.config.active_job.custom_serializers << CertificateGradeSerializer` in an initializer, and keep it in an `autoload_once_paths` directory, since serializers are registered once at boot. In Rails 8.1 a private or missing `klass` is deprecated rather than an error.
go deeper
Know which argument types Active Job accepts and that anything else raises SerializationError when you call perform_later.
Write an ObjectSerializer subclass with serialize, deserialize and a public klass, register it, and explain the _aj_serialized key.
Plan for payload compatibility: renamed serializers or changed hash shapes break jobs already queued from the previous release.
Decide when value types deserve shared serializers and when the job contract should stay primitive for portability across backends.
## What Active Job can carry out of the box A job's arguments must survive a trip through the queue as JSON-safe data. Active Job knows how to do that for a fixed list of types: - `nil`, `true`, `false`, `String`, `Integer`, `Float`, `BigDecimal` and `Symbol` - `Date`, `Time`, `DateTime`, `ActiveSupport::TimeWithZone` and `ActiveSupport::Duration` - `Range`, `Module` and `Class` - `Array`, `Hash` (keys must be strings or symbols) and `ActiveSupport::HashWithIndifferentAccess` - anything that includes `GlobalID::Identification`, which covers every Active Record model Anything else, such as a `Data` or `Struct` value object or a plain Ruby class, makes `perform_later` raise **`ActiveJob::SerializationError`** with "Unsupported argument type", in the caller, before anything is queued. ## Three ways out 1. **Pass primitives** and rebuild the object inside `perform`. Simple, and often the right answer for one job. 2. **Give the object a GlobalID** when it can be found again by id. That needs a `find` the locator can call; a value object has none. 3. **Write a custom serializer** when the same value type crosses many jobs and you want `perform` to receive the real object. ## Writing the serializer ```ruby # app/serializers/certificate_grade_serializer.rb class CertificateGradeSerializer < ActiveJob::Serializers::ObjectSerializer def serialize(grade) super("score" => grade.score, "max_score" => grade.max_score) end def deserialize(hash) CertificateGrade.new(score: hash["score"], max_score: hash["max_score"]) end def klass CertificateGrade end end ``` The three methods each have a job: | Method | Called when | Must return | |---|---|---| | `serialize(object)` | at enqueue | a hash; calling `super` merges `"_aj_serialized" => "CertificateGradeSerializer"` | | `deserialize(hash)` | on the worker, before `perform` | the rebuilt object | | `klass` | when the serializer is registered | the class it handles, used as an index key | `ObjectSerializer` includes `Singleton`, and its default `serialize?(argument)` is `argument.is_a?(klass)`. The hash you hand to `super` is not serialized a second time, so its values should already be JSON-safe: strings, numbers, booleans, `nil`, arrays and string-keyed hashes. ## Registering it ```ruby # config/initializers/custom_serializers.rb Rails.application.config.active_job.custom_serializers << CertificateGradeSerializer ``` The Active Job guide adds that serializers are registered once during initialization and are not reloadable, so their directory belongs in `autoload_once_paths`: ```ruby # config/application.rb config.autoload_once_paths << "#{root}/app/serializers" ``` ## What changed in Rails 8.1 - `ObjectSerializer#klass` became **public**, and Active Job now uses `klass` to index serializers for faster lookup. - A custom serializer whose `klass` is private, or which has no `klass` at all, triggers a **deprecation warning** at registration; the warning says it will raise in Rails 8.2, which has not shipped. Serializers written for earlier releases often define `klass` as a private method, and that form is now the deprecated one. ## Choosing between the options | | Primitives | GlobalID | Custom serializer | |---|---|---|---| | What `perform` receives | raw values | the record, reloaded | the rebuilt object | | State it reflects | enqueue time | perform time | enqueue time | | Setup | none | the object must be findable by id | a class, an initializer, a load path | | Deploy risk | low | renamed models | renamed serializers, changed hash keys | A serializer is the heaviest of the three, so it earns its place only when the same value type travels through several jobs. ## Operational traps - **Renaming a serializer breaks jobs already queued.** The payload stores the serializer's class name, and deserialization looks it up with `safe_constantize`. A missing serializer raises `ArgumentError`, which Active Job wraps in `ActiveJob::DeserializationError`. Keep the old name until old jobs have drained. - **Changing the hash shape** has the same effect: jobs enqueued by the previous release still carry the old keys, so `deserialize` should tolerate both for one deploy. - **Serializers do not make an object current.** Unlike a GlobalID, a serialized value is a snapshot taken at enqueue time, which is exactly what you want for a grade awarded at completion.
- When is a custom serializer the wrong tool compared with passing primitives?When one job uses the value once. Passing `grade.score` and `grade.max_score` and building the object inside `perform` needs no global registration, no boot-time loading rules and no payload-compatibility concerns across deploys. A serializer pays off when the same value type travels through many jobs.
- What happens to queued jobs if you rename CertificateGradeSerializer in a deploy?Their payloads still name the old class under `_aj_serialized`. On the worker, Active Job looks it up with `safe_constantize`, finds nothing and raises `ArgumentError` ("Serializer ... is not known"), which becomes `ActiveJob::DeserializationError`. Keep the old class, or an alias, until the queue has drained.
- Active Job falls back to to_h for any object it cannot serialize
- An unsupported argument only fails later, on the worker
- klass can stay private in Rails 8.1 with no warning
- A serialized value object is reloaded fresh from the database like a GlobalID
- Serializers are reloaded on every request in development like models
Assumes Rails 8.1, where ObjectSerializer#klass is public and a private or missing klass on a custom serializer is deprecated.