Consider the situation where a model is created to which the data needs to manipulated/worked with right after creation. For instance find (
*match) a certain string from a long string, convert (parts of) the long string to PDF, upload some attachments to S3, etc.
The most obvious way to me, would be to put all this separate model's methods in a background worker.
But I was also thinking of extracting these methods into some rake task (which can then also be moved to a background queue).
Basically just curious if there are other ways to go about this. Maybe I am overthinking, but who knows (at this time of the year… ;)).
This would be a good place to write a Ruby class that handles the processing, and then you can call that class and pass in the objects you need from background workers or rake tasks. Since the class would be agnostic, you can use the background worker or rake task to feed in the inputs like the model you need to process and the work can be done in either spot with the same code. Having a rake task is easy for testing, and then background jobs are important for production tasks, so a Ruby class would let you do that nicely.
Something like this:
# Your processing class class ProcessWhatever def perform(model_id) model = Model.find(model_id) # do your work here end end
# Your background worker can call it class ProcessJob < ApplicationJob def perform(model_id) ProcessWhatever.new.perform(model_id) end end
# Rake task task :process_whatever do ProcessWhatever.new.perform(YOUR_ID_FROM_ARGS) end
Just to +1 what Chris said - this is the perfect scenario for service objects! If you haven't already, check out his video on PORO's - https://gorails.com/episodes/wrapping-business-logic-with-plain-old-ruby-objects
There are a ton of articles on the interwebz (keywords: ruby poro or ruby service objects) that I would strongly suggest reading since the whole idea is more about organization of code more so than core functionality once you understand how to use them.
Good luck! :)
Thanks both Chris and Jacob. Really helpful. 🙌 I got some viewing and reading to do.
Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.