Skip to content

Commit c9af348

Browse files
authored
Merge pull request #149 from workgena/slice_insert_columns
Add possibility to skip columns/values in CSV
2 parents b491d73 + fbd2459 commit c9af348

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

lib/active_admin_import/importer.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,30 @@ def batch_replace(header_key, options)
6060
end
6161
end
6262

63+
# Use it when CSV file contain redundant columns
64+
#
65+
# Example:
66+
#
67+
# ActiveAdmin.register Post
68+
# active_admin_import before_batch_import: lambda { |importer|
69+
# importer.batch_slice_columns(['name', 'birthday'])
70+
# }
71+
# end
72+
#
73+
def batch_slice_columns(slice_columns)
74+
use_indexes = []
75+
headers.values.each_with_index do |val, index|
76+
use_indexes << index if val.in?(slice_columns)
77+
end
78+
return csv_lines if use_indexes.empty?
79+
# slice CSV headers
80+
@headers = headers.to_a.values_at(*use_indexes).to_h
81+
# slice CSV values
82+
csv_lines.map! do |line|
83+
line.values_at(*use_indexes)
84+
end
85+
end
86+
6387
def values_at(header_key)
6488
csv_lines.collect { |line| line[header_index(header_key)] }.uniq
6589
end

spec/import_spec.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,43 @@ def upload_file!(name, ext = 'csv')
433433
end
434434
end
435435

436+
context "with slice_columns option" do
437+
before do
438+
add_author_resource template_object: ActiveAdminImport::Model.new,
439+
before_batch_import: lambda { |importer|
440+
importer.batch_slice_columns(slice_columns)
441+
}
442+
visit "/admin/authors/import"
443+
upload_file!(:authors)
444+
end
445+
446+
context "slice last column and superfluous column" do
447+
let(:slice_columns) { %w(name last_name not_existing_column) }
448+
449+
it "should not fill `birthday` column" do
450+
expect(Author.pluck(:name, :last_name, :birthday)).to match_array(
451+
[
452+
["Jane", "Roe", nil],
453+
["John", "Doe", nil]
454+
]
455+
)
456+
end
457+
end
458+
459+
context "slice column from the middle" do
460+
let(:slice_columns) { %w(name birthday) }
461+
462+
it "should not fill `last_name` column" do
463+
expect(Author.pluck(:name, :last_name, :birthday)).to match_array(
464+
[
465+
["Jane", nil, "1988-11-16".to_date],
466+
["John", nil, "1986-05-01".to_date]
467+
]
468+
)
469+
end
470+
end
471+
end
472+
436473
context 'with invalid options' do
437474
let(:options) { { invalid_option: :invalid_value } }
438475

0 commit comments

Comments
 (0)