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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.