When importing a CSV file with Rails, I implemented it like this.
def read_csv
begin
rows = CSV.read(file, encoding: 'UTF-8')
rescue CSV::MalformedCSVError
begin
#csv file is UTF-Shift if not 8_Read in JIS
rows = CSV.read(file, encoding: 'Shift_JIS')
rescue CSV::MalformedCSVError, Encoding::InvalidByteSequenceError, Encoding::UndefinedConversionError
#csv file is UTF-8 ・ Shift_If it is not JIS
@error = 'File encoding is UTF-8 or Shift_It is not JIS.'
end
end
rows&.shift #Remove header
rows
end
There are a lot of exception handling and it is troublesome, and there are only two character codes that can be imported in the first place ...
Apparently anything can be converted using a module called nkf
...
https://docs.ruby-lang.org/ja/latest/class/NKF.html
--Install nkf on your PC
brew install nkf
nkf -w --overwrite path of the file you want to convert
If you use this command, you can convert it to a good feeling.
--Try embedding this command in Rails.
def read_csv(file)
system("nkf -w --overwrite #{file.path}")
rows = CSV.read(file)
rows&.shift #Remove the header on the first line
rows
end
The code is clean.
Please note that you cannot use the nkf
command unless you install nkf with the brew install nkf
command etc. in advance.
Recommended Posts