我用谷歌搜索了这个似乎无法找到
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失败,因为它在ApplicationController中设置。
所以让我们修改一下我的问题:最好的做法是将current_user.id作为参数添加到我的模块方法中,或者以某种方式将它保存在Application Controller等中。
如果我完全偏离这里并且这种逻辑应该去其他地方,请告诉我。
答案 0 :(得分:2)
您可以通过执行以下操作来完成此行为:
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
为任何愚蠢的语法错误道歉,但这或多或少是您想要的结构。
话虽这么说,在这种情况下使用模块可能有点过头了,特别是如果你不打算在其他地方重新使用它的方法。在这种情况下,我只需在工作者中添加一个私有方法。