Search code examples
ruby-on-railsredisworkersidekiq

multiple methods per sidekiq worker


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!


Solution

  • 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.