Serializable Service Objects
I have to admit, I really like using Service Objects when I’m working in Rails. By which I mean, a tableless object that has domain knowledge for a particular interaction.
They make it easy to keep the bundle of logic together. . .but I’m not writing to talk about service objects in general.
This post is about how to make them ActiveJob compliant and work with Sidekiq.
Let’s say we are trying to coordinate a couple service objects, and one of them really should be run as a background job:
Contrived example, so what’s new? ;)
Let’s introduce a concern so we can easily convert
Manhattan to be serializable.
So we’re basically saying that our little class is fully definable by a GlobalID composed of whatever we put in the attributes hash.
Unsurprisingly then, we need to add that to our class.
Now when you pass it off to the
HipsterMixer, the GlobalID generated for your background job will be a JSON-serialized representation of the Service Object.
Usual caveats are implied (be careful how much data you serialize, ids not objects, etc.)