14
votes

I don't get it.

Per Sidekiq documentation, each worker (mine is called FeedWorker) can only contain one method called perform. Well, what if I want to run mulitple methods through the same worker?

For instance, my FeedWorker (you guessed it, it processes an activity feed) should run the following 3 methods:

announce_foo
announce_bar
invite_to_foo

I don't think this is an unreasonable expectation. I'm sure other folks have considered this. I'm no genius, but I know I'm not breaking new ground in expectations here. Yet it's not clear how one would do this.

Right now, it looks like I have to code this way:

def perform(id, TYPE)
  if TYPE == BAR
    Bar.find(id) and_announce_bar
  else
    Foo.find(id) and_announce_foo
  end
end

Boring and ugly code. There must be better out there. Any help appreciated!

2
Can you link to the docs page where you found such statement? - Fabrizio Regini

2 Answers

7
votes

perform method is the entry point of your Worker. Inside of it you can create as many instance methods as you want, to organize your code as it best fits your need. It's a good practice though to keep worker code as slim as possible. Calling other objects from inside of it for example is a way to achieve that. You'll find your code will be easier to test too.

3
votes

I had the same question for awhile and now have a rather simple solution: use the Delayed Extension method on any class, as explained in docs, for ex:

# Usage: EmailWorker.delay.do_something

class EmailWorker
  class << self
    def send_this(attrs)
      MyMailer.some_action(attrs).deliver
    end

    def send_that(attrs)
      MyMailer.another_action(attrs).deliver
    end
  end
end

Any class can be delayed, so no need to include Sidekiq::Worker if you're not going to use perform_async method.

The problem I've had with this is that the per-worker options won't be used unless you go thru the perform_async method.