【问题标题】:Using a Controller Method with Resque Background Job使用带有 Resque 后台作业的控制器方法
【发布时间】:2016-07-14 15:28:44
【问题描述】:

我在 Rails 4 上使用带有 Redis 的 Resque。

我的问题:如何在后台作业中使用当前在 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

我想在 delay_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

提前感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    push_to_google 提取(移动)到ApplicationHelper,并将ApplicationHelper 包含在您的ApplicationControllerDelayedNotifications 中。

    更改后,您的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
    

    【讨论】:

    • 我不会把它放到ApplicationHelper 中,而是在lib/ 的某个地方放置一个专用模块。您的方法对我来说似乎很危险,因为它将ApplicationHelper 中定义的所有方法添加为控制器操作。出于这个原因,我会将该方法包含为私有。
    • 感谢您的评论,我想我会采用这种方法。将我的模块放入 lib 目录与 helpers 目录有什么好处吗? @BoraMa
    • @Kathan 略有不同。 Rails helpers(即app/helpers 目录中的模块)是为moving complex logic out of the views 设计的,即它们通常处理数据的呈现。此外,默认情况下,所有助手都包含在视图命名空间中(它们可以从视图中自动使用)。 lib 目录通常用于任何支持模块。由于您的代码似乎不处理演示文稿,我将其放入lib
    • 即使包含app/helpers 将使这些模块方法成为controller 上的公共方法,这意味着这些方法可以是actions,除非您定义一个路线。即使你定义了一个路由,除非你定义一个相应的视图,否则它们也不会起作用。所以,我不会偏执于这种方法很危险。
    • 但正如@BoraMa 提到的,通常,app/helpers 是复杂视图逻辑所在。并且您会将应用程序特定的逻辑保留在lib 目录下。同时,没有什么能阻止您在我的回答中采用这种方法。如果是一种或两种方法,我倾向于将其保存在app/helpers 中,但如果列表开始增长/变得复杂,我会将它们移至lib 文件夹。原因是app/helpers已经在authload_paths下,但是lib,根据rails的版本,需要添加到autoload_paths下。
    猜你喜欢
    • 2016-05-29
    • 2016-08-05
    • 2019-07-31
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2012-09-14
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多