Skip to content

Instantly share code, notes, and snippets.

@jonleighton
Created June 11, 2014 11:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonleighton/7654d81ddb6309ecd305 to your computer and use it in GitHub Desktop.
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
@mperham
Copy link

mperham commented Jun 11, 2014

Here's what's idiomatic for Sidekiq:

class TaskWorker
  include Sidekiq::Worker

  def perform(task_id)
    t = Task.find(task_id)
  end
end

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.

@jonleighton
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment