Ask A Question

Notifications

You’re not receiving notifications from this thread.

Where do this code go? (Refactoring Rails Workers)

Arjun Rajkumar asked in Rails

Hey!

I have two different workers

#app/workers/website_worker.rb
class WebsiteWorker

  def perform(website)
    do_this_action(website)
  end

  def do_this_action(website)
    ...
  end
end
#app/workers/event_worker.rb
class EventWorker

  def perform(event)
    event.update(alive: true)
    website = Website.find_by url: event.url
    do_this_action(website)
  end

  def do_this_action(website)
    ...
  end
end

The do_this_action code is repeated twice in two different workers.
The do_this_action uses Nokigiri to crawl a website, and then updates database accordingly.
Wondering what are the best practices to refactor this code?

Thanks.

Reply

Is it running the job twice? There's nothing here that would duplicate the calling of do_this_action that I can see.

Reply

Sorry.. Didnt explain this properly.

Both these different jobs website_worker and event_worker are run at different times. But in these two differrent jobs, the same function do_this_action is being called. The do_this_action does the same thing while being called via both these different workers.

So I was wondering if I can move the code in do_this_action to some place and then include/require it in the two different workers - so that the code is not repeated.

Reply

Have update the code in event_worker.rb

Reply

Ah yes, sorry! :)

I would pull the logic out into its own class. You can either make it a base class for the job, or you can make it a dedicated class.

This example is the inheritance approach:

class BaseWorker
  def do_this_action(website)
    ...
  end
end

class WebsiteWorker < BaseWorker

  def perform(website)
    do_this_action(website)
  end
end

Or if you wanted a dedicated class:

class DoThisProcessor
  def perform(website)
  end
end

class WebsiteWorker
  def perform(website)
    DoThisProcessor.new.perform(website)
  end
end

They're both very simple so you won't have too many tradeoffs either way you go in this case.

Reply

Thank you!! Solved.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.