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.
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.
Heres where it breaks:
WARN: ArgumentError: undefined class/module CsvImport
The method being called in 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
config.autoload_paths += Dir["#{config.root}/app/services"]
More details here: autoload-paths
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.