LoginSignup
0
0

Ruby Rails そのCSVどんな文字コードだろうと取り込んでやるよ

Last updated at Posted at 2024-04-17

文字コード...

...日本で開発をしている皆さん。こんにちは。文字コードです😈

もう嫌なんだ

  • CSVが取り込めない?
  • 文字コード?
  • UTF-8?
  • SHIFT-JIS?
  • BOM?
  • BOM付?え?
  • ローカルではいける?
  • あの人は取り込めないらしい?
  • Macならいける?
  • Windowsならいけない?
  • エクセルで開いた?
  • メモ帳で保存して?
  • スプレッドシートから出力?
  • 取り込めないんですけど😡?
  • こっちでは取り込めるんだよなあ?
  • ああああああああああああああああああ

どんなものでも取り込めるそんな魔法のような実装はないのかね

あるかもしれない、ないかもしれない。
僕が辿り着いたところはここまでだ。
効率がいいか?そんなことはしらん。
いいから魔改造だ!

require 'csv'
require 'nkf'

def import_csv(file_param)
  # どんなものでも取り込めるように魔改造
  file_encoding = NKF.guess File.read(file_param.path)
  File.open(file_param.path,
            "rt:BOM|#{file_encoding}",
            universal_newline: true,
            undef: :replace,
            invalid: :replace,
            replace: '') do |file|
    CSV.new(file,
            liberal_parsing: true,
            headers: true,
            converters: nil,
            header_converters: :symbol,
            skip_lines: /^(?:,\s*)+$/,
            col_sep: ',',
            quote_char: '"').each do |row|
      product = Product.find_by(id: row['ID'])
      product.update(name: row['名前'], price: row['価格'])
    end
  end
end

参考にさせていただきました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0