Skip to content

Instantly share code, notes, and snippets.

@katsyoshi
Last active August 13, 2019 15:15
Show Gist options
  • Save katsyoshi/bfd86639d9464f60f27b26e20a85c720 to your computer and use it in GitHub Desktop.
Save katsyoshi/bfd86639d9464f60f27b26e20a85c720 to your computer and use it in GitHub Desktop.
class BomUtf8CSV
attr_reader :has_bom
UTF_8_BOM = "\xEF\xBB\xBF".b
def initialize(io)
io.rewind if io.respond_to?(:rewind)
@has_bom = io.read(UTF_8_BOM.length) == UTF_8_BOM
io.rewind unless @has_bom
@io = io
@csv = CSV.new(@io, { headers: true })
end
def headers
@csv.rewind
@io.read(UTF_8_BOM.length) if @has_bom
CSV.new(@io, { headers: false }).shift
end
end
require 'csv'
input = StringIO.new.tap(&:binmode)
input.write "\xEF\xBB\xBF"
input.puts "num,bar,baz"
input.puts "123,aaa,1.1"
input.puts "234,bbb,2.2"
puts "CSV::VERSION: #{CSV::VERSION}"
csv = BomUtf8CSV.new(input)
puts csv.headers == %w|num bar baz|
# when csv <= 3.0.1 #=> true
# when csv > 3.0.1 #=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment