ruby-on-rails 如何在本地将我所有的“perform_later”转换为“perform_now "?

xytpbqjk  于 7个月前  发布在  Ruby
关注(0)|答案(3)|浏览(87)

我正在开发一个需要perform_later作业的产品,这对我们的产品在生产中是有效的,因为我们有一系列的工人来运行所有的作业。
但是,当我在本地使用该应用程序时,我无法访问这些工作人员,并且我希望仅在 * 本地使用该应用程序时 * 才将所有perform_later s更改为perform_now s。
我的一个想法是在我的env文件中添加一些东西,它将添加一个变量,使所有的perform_later s变成perform_now s --但我不确定这样的标志或变量是什么样子。
想法?

ny6fqffe

ny6fqffe1#

干净的解决方案是在开发环境中更改queue_adapter
config/environments/development.rb中,您需要添加:

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

字符串
“使用内联适配器封装作业时,作业将立即执行。”

2wnc66cl

2wnc66cl2#

在您的应用程序中,您可以:

  • /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

字符串
此mixin仅包含在testdevelopment环境中。
那么,如果你的工作是:

  • /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">


请记住:这样做,所有作业将立即在测试和开发环境中执行。如果您想为单个作业启用此功能,则只需在该作业中包含JobsExt mixin。

kdfy810k

kdfy810k3#

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

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

字符串
简单地更新环境,

相关问题