Rails + Sidekiq没有认识到课程

时间:2017-02-15 18:46:01

标签: ruby-on-rails redis backgroundworker sidekiq

我的CsvImport中有一个app/services服务对象,我试图从一个Worker中调用一个类方法。

class InventoryUploadWorker
  include Sidekiq::Worker

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

但似乎工人不知道班级是什么,我试图require 'csv_import'无济于事。

Heres断断续续的地方:

WARN: ArgumentError: undefined class/module CsvImport

调用方法 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

2 个答案:

答案 0 :(得分:0)

你的要求在课堂上。将它们放在课外,这样在加载文件时就可以立即使用它们,而不是在加载类时。

而不是

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

这样做

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

答案 1 :(得分:-1)

尝试添加到application.rb

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

此处有更多详情:autoload-paths