-
-
Save jonleighton/7654d81ddb6309ecd305 to your computer and use it in GitHub Desktop.
# This pattern avoids serializing a large object (the Task) to Redis, whilst | |
# avoiding passing a low-level data type (the id) into the constructor. | |
# You might choose to call TaskJob.new(task) directly elsewhere (e.g. tests) | |
class TaskJob | |
def self.perform(id) | |
new(Task.find(id)).perform | |
end | |
def initialize(task) | |
@task = task | |
end | |
def perform | |
# ... | |
end | |
end |
I presume you meant:
def perform(task_id)
t = Task.find(task_id)
t.some_work
end
?
Sometimes there's a bunch of other "stuff" to do before I actually want to call into one of my domain objects. That has to go somewhere, and whilst it could go somewhere else, it seems more straightforward to me to just put it in the worker/job object.
Also, sometimes the stuff I'm doing in a worker/job object is quite messy stuff unrelated to my core domain model. For example I have a job which periodically runs some queries and submits some metrics to Librato Metrics. Again one argument is that I should create another MetricsSubmitter
object or something, and then just instantiate that from my MetricsSubmitterWorker
. Which is fair enough but it just feel like an unnecessary amount of ceremony for such a quick-and-dirty task. So I prefer to put it in my worker/job object.
Here's what's idiomatic for Sidekiq:
No need for a class-level perform or initialize method. No vestigial perform method or saving the args to ivars. Guarantees the worker can be instantiated with no args.