如何在本地将我所有的“perform_later”转换为“perform_now”?

How can I turn all my 'perform_later's into 'perform_now's locally?

我正在开发一种需要 perform_later 个工作的产品。这适用于我们生产中的产品,因为我们有一系列工人将 运行 所有工作。

但是,当我在本地使用该应用程序时,我无法访问这些工作人员,我想将所有 perform_later 更改为 perform_now 仅当 我在本地使用该应用程序时。

最好的方法是什么?我的一个想法是在我的 env 文件中添加一些东西,该文件将添加一个变量以使所有 perform_laters 变成 perform_nows - 但我不确定标志或变量是什么就像那样。

想法?

我们通过调用一个中间方法解决了这个问题,然后根据 Rails 配置调用 perform_later 或 perform_now:

def self.perform(*args)
  if Rails.application.config.perform_later
    perform_later(*args)
  else
    perform_now(*args)
  end
end

并相应地更新环境配置

在您的应用中,您可以拥有:

/my_app/config/initializers/jobs_initializer.rb

module JobsExt
  extend ActiveSupport::Concern

  class_methods do
    def perform_later(*args)
      puts "I'm on #{Rails.env} envirnoment. So, I'll run right now"
      perform_now(*args)
    end
  end
end

if Rails.env != "production"
  puts "including mixin"
  ActiveJob::Base.send(:include, JobsExt)
end

This mixin will be included on test and development environments only.

那么,如果您在以下工作:

/my_app/app/jobs/my_job.rb

class MyJob < ActiveJob::Base
  def perform(param)
    "I'm a #{param}!"
  end
end

您可以执行:

MyJob.perform_later("job")

并得到:

#=> "I'm a job!"

而不是作业实例:

#<MyJob:0x007ff197cd1938 @arguments=["job"], @job_id="aab4dbfb-3d57-4f6d-8994-065a178dc09a", @queue_name="default">

Remember: Doing this, ALL your Jobs will be executed right now on test and dev environments. If you want to enable this functionality for a single job, you will need to include the JobsExt mixin in that job only.

干净的解决方案是在开发环境中change the adapter

在您的 /config/environments/development.rb 中您需要添加:

Rails.application.configure do
  config.active_job.queue_adapter = :inline
end

"When enqueueing jobs with the Inline adapter the job will be executed immediately."