[英]How to share methods between rails sidekiq workers
我在 Rails 应用程序中有两个 sidekiq 工作人员,我想知道在他们之间共享代码的最佳方式是什么。
class PriceReminderWorker
include Sidekiq::Worker
sidekiq_options queue: 'price_alerts'
def method_to_share
stuff
end
end
和
class PriceNotificationWorker
include Sidekiq::Worker
sidekiq_options queue: 'price_alerts'
def method_to_share
stuff
end
end
'rails/ruby 方式'会从父 class 继承,还是添加一个新模块?
如果对您有意义,我会使用 inheritance,例如PriceReminderWorker
和PriceNotificationWorker
都是PriceWorker
并且您想要共享的方法在PriceWorker
上下文中有意义。 例如,在 Rails 中,所有模型都是ApplicationRecord
是有道理的
如果您要共享的方法仅利用两个类共享的一些共同“特征”,我会将这些方法包含在模块中。 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. 在这种情况下,两个类都包含Enumerable
模块。
您可以将共享方法放在一个模块中,然后将它们包含在您的工作人员类中。
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
两个工作类现在都可以访问模块中定义的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.