使用Resque后台作业的控制器方法

时间:2016-03-27 05:45:49

标签: ruby-on-rails ruby-on-rails-4 controller redis resque

我使用Resque w / Redis在Rails 4上。

我的问题:如何在我的后台作业中使用当前在application_controller中定义的控制器方法?

这是我定义的当前方法:

def push_to_google(token, message)
  if token.present?
    gcm = GCM.new("843jf9384fj839f848j890fj3")
    registration_ids = ["#{token}"] # an array of one or more client registration tokens
    options = {data: {notification: "#{message}"}}
    response = gcm.send(registration_ids, options)
  end
end

我想在我的delayed_notifications中定义的后台作业中使用:

class DelayedNotifications
  @queue = :notifications_queue

  def self.perform(registration_id, user_name)
    push_to_google(registration_id, "New message from #{user_name}.")
  end
end

当然,我的工作目前无法解决此错误:

undefined method 'push_to_google' for DelayedNotifications:Class

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

push_to_google提取(移动)到ApplicationHelper,并在ApplicationHelperApplicationController中添加DelayedNotifications

更改后,您的application_helper.rb应为:

module ApplicationHelper
  # other methods

  def push_to_google(token, message)
    if token.present?
      gcm = GCM.new("843jf9384fj839f848j890fj3")
      registration_ids = ["#{token}"] # an array of one or more client registration tokens
      options = {data: {notification: "#{message}"}}
      response = gcm.send(registration_ids, options)
    end
  end
end 

application_controller.rb

class ApplicationController < ActionController::Base
  include ApplicationHelper

end

delayed_notifications.rb

class DelayedNotifications
  include ApplicationHelper

  @queue = :notifications_queue

  def self.perform(registration_id, user_name)
    push_to_google(registration_id, "New message from #{user_name}.")
  end
end