簡體   English   中英

如何在 rails sidekiq 工作人員之間共享方法

[英]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,例如PriceReminderWorkerPriceNotificationWorker都是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM