You’re not receiving notifications from this thread.
Where do this code go? (Refactoring Rails Workers)
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
do_this_action code is repeated twice in two different workers.
do_this_action uses Nokigiri to crawl a website, and then updates database accordingly.
Wondering what are the best practices to refactor this code?
Is it running the job twice? There's nothing here that would duplicate the calling of
do_this_action that I can see.
Sorry.. Didnt explain this properly.
Both these different jobs
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.
Have update the code in event_worker.rb
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.
Thank you!! Solved.