Module: CSVUtils::ByteOrderMark
- Defined in:
- lib/csv_utils/byte_order_mark.rb
Overview
Detects and strips the byte order mark at the start of a CSV file.
Constant Summary collapse
- ENCODINGS =
Byte order marks, as binary strings, to the encoding they indicate. This list is from https://en.wikipedia.org/wiki/Byte_order_mark. UTF-32 LE starts with the UTF-16 LE mark, so longer marks come first.
{ (+"\x00\x00\xFE\xFF").force_encoding('ASCII-8BIT').freeze => 'UTF-32', (+"\xFF\xFE\x00\x00").force_encoding('ASCII-8BIT').freeze => 'UTF-32', (+"\xEF\xBB\xBF").force_encoding('ASCII-8BIT').freeze => 'UTF-8', (+"\xFE\xFF").force_encoding('ASCII-8BIT').freeze => 'UTF-16', (+"\xFF\xFE").force_encoding('ASCII-8BIT').freeze => 'UTF-16' }.freeze
Class Method Summary collapse
-
.detect(str) ⇒ String?
The byte order mark the string starts with.
-
.strip(str) ⇒ String
The string without its leading byte order mark, in its original encoding.
Class Method Details
.detect(str) ⇒ String?
The byte order mark the string starts with. Compares bytes, so it works whatever the string's encoding is.
21 22 23 24 |
# File 'lib/csv_utils/byte_order_mark.rb', line 21 def self.detect(str) prefix = str.byteslice(0, 4).b ENCODINGS.keys.detect { |bom| prefix.start_with?(bom) } end |
.strip(str) ⇒ String
The string without its leading byte order mark, in its original encoding.
29 30 31 32 |
# File 'lib/csv_utils/byte_order_mark.rb', line 29 def self.strip(str) bom = detect(str) bom ? str.byteslice(bom.bytesize..) : str end |