Skip to content

Commit

Permalink
Merge fbd2459 into b491d73
Browse files Browse the repository at this point in the history
  • Loading branch information
workgena committed Apr 10, 2018
2 parents b491d73 + fbd2459 commit 4981d11
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/active_admin_import/importer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,30 @@ def batch_replace(header_key, options)
end
end

# Use it when CSV file contain redundant columns
#
# Example:
#
# ActiveAdmin.register Post
# active_admin_import before_batch_import: lambda { |importer|
# importer.batch_slice_columns(['name', 'birthday'])
# }
# end
#
def batch_slice_columns(slice_columns)
use_indexes = []
headers.values.each_with_index do |val, index|
use_indexes << index if val.in?(slice_columns)
end
return csv_lines if use_indexes.empty?
# slice CSV headers
@headers = headers.to_a.values_at(*use_indexes).to_h
# slice CSV values
csv_lines.map! do |line|
line.values_at(*use_indexes)
end
end

def values_at(header_key)
csv_lines.collect { |line| line[header_index(header_key)] }.uniq
end
Expand Down
37 changes: 37 additions & 0 deletions spec/import_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,43 @@ def upload_file!(name, ext = 'csv')
end
end

context "with slice_columns option" do
before do
add_author_resource template_object: ActiveAdminImport::Model.new,
before_batch_import: lambda { |importer|
importer.batch_slice_columns(slice_columns)
}
visit "/admin/authors/import"
upload_file!(:authors)
end

context "slice last column and superfluous column" do
let(:slice_columns) { %w(name last_name not_existing_column) }

it "should not fill `birthday` column" do
expect(Author.pluck(:name, :last_name, :birthday)).to match_array(
[
["Jane", "Roe", nil],
["John", "Doe", nil]
]
)
end
end

context "slice column from the middle" do
let(:slice_columns) { %w(name birthday) }

it "should not fill `last_name` column" do
expect(Author.pluck(:name, :last_name, :birthday)).to match_array(
[
["Jane", nil, "1988-11-16".to_date],
["John", nil, "1986-05-01".to_date]
]
)
end
end
end

context 'with invalid options' do
let(:options) { { invalid_option: :invalid_value } }

Expand Down

0 comments on commit 4981d11

Please sign in to comment.