在 Sidekiq worker 中调用 Rails 应用程序帮助程序



我已经用谷歌搜索了这个,似乎找不到

class MyWorker
  include Sidekiq::Worker
  include ApplicationHelper
  worker code.... etc....
  myapphelper(arg)
end

我有一个简单的工作线程,最后调用应用程序助手,但我得到:

NoMethodError: undefined method `myapphelper'

我认为添加include ApplicationHelper就可以了。

更新

因此,让我们添加更多细节。 有问题的帮助程序(实际上是我的应用程序控制器中的一个方法)最初是这样的:

def add_history(resource, action, note)
    resource.history.create(action: action, note: note, user_id: current_user.id) if resource.present? && action.present? && note.present?
end

这里的想法是我有一种快速的方法向模型添加书面记录。 我意识到我可能不应该将实际对象传递到方法中,因为(如 Sidekiq 文档所示)如果该对象发生变化,您可能会遇到麻烦。 所以我把它改成这样:

  def add_history(klass, id , action, note)
    resource = klass.constantize.find_by(id: id)
    resource.history.create(action: action, note: note, user_id: current_user.id) if resource.present? && action.present? && note.present?
  end

现在,当我将其作为模块包含时,current_user.id 失败,因为它是在应用程序控制器中设置的。

因此,让我们修改我的问题:最佳做法是将 current_user.id 作为参数添加到我的模块方法中,还是以某种方式将其保留在应用程序控制器等中?

如果我在这里完全偏离轨道,这种类型的逻辑应该去其他地方,请告诉我。

您可以通过执行以下操作来完成该行为:

class HistoryWorker
   include Sidekiq::Worker
   include History # or whatever you want to call it
  def perform(klass, id , action, note, user_id)
    add_history(klass, id, action, note, user_id)
  end
end
module History
  def add_history(klass, id, action, note, user_id)
    resource = klass.constantize.find_by(id: id)
    resource.history.create(action: action, note: note, user_id: user_id) if resource.present? && action.present? && note.present?
  end
end
class ApplicationController < ActionController::Base
  after_filter :save_history
  def save_history
     HistoryWorker.perform_async(class: resource.class.name, id: resource.id, action: params[:action], note: 'some note', user_id: current_user.id)
  end
end

为任何愚蠢的语法错误道歉,但这或多或少是你想要的结构。

话虽如此,在这种情况下使用模块可能是矫枉过正的,特别是如果您不打算在其他地方重用其方法。 在这种情况下,我只需在 worker 中添加一个私有方法。

相关内容

最新更新