简体   繁体   中英

how do I use rails helpers in resque jobs?

I'm trying to use some helpers in my resque job and am running into problems. Here's what I've tried:

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

I also need to include the helper with the image_path method and a custom helper of mine located in module ImageHelper.

Add a named route in your config/routes.rb file and then call it from your job class (no need to include anything)

Rails.application.routes.url_helpers.following_user_url(following_user)

You also have to set in your environment the default host since you are inside 'resque' and there are no http parameters set.

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

Alternatively you can include the url_helpers and do something like this in your class

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM