如何在 Resque 作业中使用 Rails 辅助方法?

7

我正在尝试在我的Resque作业中使用一些辅助工具,但遇到了问题。这是我尝试过的内容:

require 'json'

class SoulmateUserFollowing
  tried this -> include Rails.application.routes.url_helpers
  and this -> include ActionView::Helpers:UrlHelper
  and this -> helper ActionView::Helpers::UrlHelper

  @queue = :soulmate_user

  def self.perform(user_id)
    user = User.find(user_id)
    url = url_for(following_user)
  end
end

我还需要包含具有image_path方法的helper和我自己编写的位于ImageHelper模块中的自定义helper。

1个回答

9
在你的config/routes.rb文件中添加一个命名路由,然后从你的job类中调用它(不需要包含任何内容)。
Rails.application.routes.url_helpers.following_user_url(following_user)

由于您在'resque'内部且没有设置http参数,因此还需要在环境中设置默认主机。

routes.default_url_options = {:host => "somehost.com"}

或者你可以包含url_helpers并在你的类中执行以下操作

class SoulmateUserFollowing
  include Rails.application.routes.url_helpers

  @queue = :soulmate_user

  def initialize(user_id)
    user = User.find(user_id)
    url = url_for(following_user)
  end

  def self.perform(user_id)
    new(user_id)
  end
end

太好了,它起作用了。然而,我仍然不明白为什么包括url_helpers,然后调用user_path(user)或其他内容不起作用?另外,我需要弄清楚如何包括rails资产助手以获取image_path和我自己的ImageHelper模块,该模块位于普通的rails助手文件夹中。有任何想法吗? - Marc
它应该通过扩展url_helpers或ImageHelper来工作,因为您在类方法而不是实例方法中,但是其他东西也可能会丢失。 - bandito

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接