Refactor FoodsoftFile to reuse the code later

This commit is contained in:
Patrick Gansterer 2018-09-14 20:17:46 +02:00
parent 4e1ff008bf
commit 5408c08b58
2 changed files with 39 additions and 29 deletions

View File

@ -1,5 +1,3 @@
require 'roo'
# Foodsoft-file import # Foodsoft-file import
class FoodsoftFile class FoodsoftFile
@ -7,18 +5,9 @@ class FoodsoftFile
# returns two arrays with articles and outlisted_articles # returns two arrays with articles and outlisted_articles
# the parsed article is a simple hash # the parsed article is a simple hash
def self.parse(file, options = {}) def self.parse(file, options = {})
filepath = file.is_a?(String) ? file : file.to_path SpreadsheetFile.parse file, options do |row, row_index|
filename = options.delete(:filename) || filepath next if row[2].blank?
fileext = File.extname(filename)
options[:csv_options] = {col_sep: ';', encoding: 'utf-8'}.merge(options[:csv_options]||{})
s = Roo::Spreadsheet.open(filepath, options.merge({extension: fileext}))
row_index = 1
s.each do |row|
if row_index == 1
# @todo try to detect headers; for now using the index is ok
elsif !row[2].blank?
article = {:order_number => row[1], article = {:order_number => row[1],
:name => row[2], :name => row[2],
:note => row[3], :note => row[3],
@ -33,9 +22,6 @@ class FoodsoftFile
status = row[0] && row[0].strip.downcase == 'x' ? :outlisted : nil status = row[0] && row[0].strip.downcase == 'x' ? :outlisted : nil
yield status, article, row_index yield status, article, row_index
end end
row_index += 1
end
row_index
end end
end end

24
lib/spreadsheet_file.rb Normal file
View File

@ -0,0 +1,24 @@
require 'roo'
class SpreadsheetFile
def self.parse(file, options = {})
filepath = file.is_a?(String) ? file : file.to_path
filename = options.delete(:filename) || filepath
fileext = File.extname(filename)
options[:csv_options] = {col_sep: ';', encoding: 'utf-8'}.merge(options[:csv_options]||{})
s = Roo::Spreadsheet.open(filepath, options.merge({extension: fileext}))
row_index = 1
s.each do |row|
if row_index == 1
# @todo try to detect headers; for now using the index is ok
else
yield row, row_index
end
row_index += 1
end
row_index
end
end