【问题标题】:how do I use rails helpers in resque jobs?如何在 resque 工作中使用 Rails 助手?
【发布时间】:2011-10-12 05:52:18
【问题描述】:

我正在尝试在我的 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 方法的助手和我的位于模​​块 ImageHelper 中的自定义助手。

【问题讨论】:

    标签: ruby-on-rails resque


    【解决方案1】:

    在您的 config/routes.rb 文件中添加一个命名路由,然后从您的作业类中调用它(无需包含任何内容)

    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) 或任何不起作用的东西?此外,我需要弄清楚如何包含 image_path 的 rails 资产助手和我自己的 ImageHelper 模块,该模块位于普通的 rails helpers 文件夹中。知道该怎么做吗?
    • 它应该通过扩展 url_helpers 或您的 ImageHelper 来工作,因为您使用的是类方法而不是实例方法,但其他东西也可能会丢失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2012-01-25
    相关资源
    最近更新 更多