Reputation: 1035
I have two sidekiq workers in a rails app and I'm wondering what the best way to share code between them would be.
class PriceReminderWorker
include Sidekiq::Worker
sidekiq_options queue: 'price_alerts'
def method_to_share
stuff
end
end
and
class PriceNotificationWorker
include Sidekiq::Worker
sidekiq_options queue: 'price_alerts'
def method_to_share
stuff
end
end
Would the 'rails/ruby way' to be inherit from a parent class, or add a new module perhaps?
Upvotes: 1
Views: 1134
Reputation: 16758
I would use inheritance if it makes sense to you for example that PriceReminderWorker
and PriceNotificationWorker
are both a PriceWorker
and the methods you want to share make sense in the PriceWorker
context. For example in Rails it makes sense that all Models are an ApplicationRecord
I would include the methods in a Module, if the methods you want to share merely take advantage of some common "trait" that both classes share. For example in Ruby both the Array class and the Hash class share a "trait", they both implement a foreach
method that can accept a block and call that block for each member of its collection. In this case both classes include the Enumerable
module.
Upvotes: 2
Reputation: 11226
You can put your shared methods in a module and just include them into your worker classes.
module Workify
def method_to_share
puts "hooray we're DRY!"
end
end
class PriceReminderWorker
include Sidekiq::Worker
sidekiq_options queue: 'price_alerts'
end
class PriceNotificationWorker
include Sidekiq::Worker
sidekiq_options queue: 'price_alerts'
end
Both worker classes now have access to the method defined in the module.
Upvotes: 0