Commit 6266c3a8 by Ivan Lan

concat options headers with import headers

parent fff7e592
...@@ -19,8 +19,7 @@ module TalltyImportExport ...@@ -19,8 +19,7 @@ module TalltyImportExport
def import_xlsx xlsx_file, associations, **options def import_xlsx xlsx_file, associations, **options
# 先处理获取出来Excel每行的数据, line_info # 先处理获取出来Excel每行的数据, line_info
options = options.with_indifferent_access options = options.with_indifferent_access
self.headers = options.delete(:headers) || {}
self.headers = options.delete(:headers) || import_headers
@primary_keys = options.delete(:primary_keys) || headers.map { |header| header[:primary_key] ? header[:key].to_sym : nil }.compact @primary_keys = options.delete(:primary_keys) || headers.map { |header| header[:primary_key] ? header[:key].to_sym : nil }.compact
excel_hash = headers.reduce({}) do |h, header| excel_hash = headers.reduce({}) do |h, header|
...@@ -76,11 +75,33 @@ module TalltyImportExport ...@@ -76,11 +75,33 @@ module TalltyImportExport
end end
def import_headers def import_headers
klass.try(:headers) || klass.try(:model_headers) klass.try(:headers) || klass.try(:model_headers) || (raise ArgumentError.new('missing import_headers'))
end end
# 只保留 key, name, json, 合并到 import_header
def headers= val def headers= val
@headers = val.map { |header| header.with_indifferent_access } if val.empty?
@headers = import_headers.map { |header| header.with_indifferent_access }
return
end
key_to_header = val.reduce({}) do |out, header|
out[header.with_indifferent_access[:key].to_sym] = header.with_indifferent_access
out
end
@headers = import_headers.map do |header|
coming_header = key_to_header[header.with_indifferent_access[:key].to_sym]
if coming_header
dup_header = header.dup
dup_header[:key] = coming_header[:key] || dup_header[:key]
dup_header[:name] = coming_header[:name] || dup_header[:name]
dup_header[:json] = coming_header[:json] || dup_header[:json]
dup_header
else
header
end
end
end end
def skip val, processing_line_info, raw_line_info def skip val, processing_line_info, raw_line_info
......
...@@ -40,7 +40,7 @@ RSpec.describe TalltyImportExport::Importable do ...@@ -40,7 +40,7 @@ RSpec.describe TalltyImportExport::Importable do
# 4 20070104 4 meta4 metaD # 4 20070104 4 meta4 metaD
# 5 20070105 5 meta5 metaE # 5 20070105 5 meta5 metaE
@result = [] @result = []
Test.import_xlsx('./spec/test1.xlsx', @result) Test.import_xlsx('./spec/test1.xlsx', @result, headers: [{ key: 'name', name: '名称' }])
expect(@result).to eq([ expect(@result).to eq([
{"name"=>1, "code"=>"20070101_1", "sub_code"=>nil, "meta"=>{"meta1"=>"meta1", "meta2"=>"metaA" }, "sum" => 1 }, {"name"=>1, "code"=>"20070101_1", "sub_code"=>nil, "meta"=>{"meta1"=>"meta1", "meta2"=>"metaA" }, "sum" => 1 },
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment