File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change @@ -60,6 +60,30 @@ def batch_replace(header_key, options)
60
60
end
61
61
end
62
62
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
+
63
87
def values_at ( header_key )
64
88
csv_lines . collect { |line | line [ header_index ( header_key ) ] } . uniq
65
89
end
Original file line number Diff line number Diff line change @@ -433,6 +433,43 @@ def upload_file!(name, ext = 'csv')
433
433
end
434
434
end
435
435
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
+
436
473
context 'with invalid options' do
437
474
let ( :options ) { { invalid_option : :invalid_value } }
438
475
You can’t perform that action at this time.
0 commit comments