简体   繁体   English

Rails + Sidekiq无法识别课程

[英]Rails + Sidekiq not recognizing class

I have a CsvImport service object in my app/services and I'm trying to call one of the class methods from within a Worker. 我的app/services有一个CsvImport服务对象,我正在尝试从Worker中调用类方法之一。

class InventoryUploadWorker
  include Sidekiq::Worker

  def perform(file_path, company_id)
    CsvImport.csv_import(file_path, Company.find(company_id))
  end
end

But it seems that the worker doesn't know what the class is, I've attempted require 'csv_import' to no avail. 但是似乎该工作人员不知道该类是什么,我试图require 'csv_import'无效。

Heres where it breaks: 破坏的地方:

WARN: ArgumentError: undefined class/module CsvImport

The method being called in csv_import.rb 在csv_import.rb中被调用的方法

class CsvImport
require "benchmark"
require 'csv'


def self.csv_import(filename, company)
    time = Benchmark.measure do
        File.open(filename) do |file|
            headers = file.first
            file.lazy.each_slice(150) do |lines|
                Part.transaction do 
                    inventory = []
                    insert_to_parts_db = []
                    rows = CSV.parse(lines.join, write_headers: true, headers: headers)
                    rows.map do |row|
                        part_match = Part.find_by(part_num: row['part_num'])
                        new_part = build_new_part(row['part_num'], row['description']) unless part_match
                        quantity = row['quantity'].to_i
                        row.delete('quantity')
                        row["condition"] = match_condition(row)
                        quantity.times do 
                            part = InventoryPart.new(
                                part_num: row["part_num"], 
                                description: row["description"], 
                                condition: row["condition"],
                                serial_num: row["serial_num"],
                                company_id: company.id,
                                part_id: part_match ? part_match.id : new_part.id
                                )           
                            inventory << part                   
                        end
                    end
                    InventoryPart.import inventory
                end
            end
        end         
    end
    puts time
end

your requires are inside the class. 您的要求在班级内。 Put them outside the class so they're required right away when the file is loaded, not when the class is loaded. 将它们放在类之外,以便在加载文件时(而不是在加载类时)立即需要它们。

Instead of 代替

class CsvImport
require "benchmark"
require 'csv'
...

Do this 做这个

require "benchmark"
require 'csv'
class CsvImport
  ...

Try to add to application.rb 尝试添加到application.rb

config.autoload_paths += Dir["#{config.root}/app/services"]

More details here: autoload-paths 此处有更多详细信息: autoload-paths

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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