Module: CSVUtils::EncodingOptions

Defined in:
lib/csv_utils/encoding_options.rb

Overview

The one place the library decides how files are decoded and encoded. Every class reads with the :encoding CSV option, 'bom|utf-8' by default, so values are UTF-8 strings whatever the locale, and writes in the encoding the values were decoded to, so reading 'Windows-1252:UTF-8' writes UTF-8. File modes never carry an encoding: CSV raises when the mode and the :encoding option both have one.

Examples:

CSV.open(path, 'rb', **CSVUtils::EncodingOptions.read(col_sep: "\t"))

Constant Summary collapse

DEFAULT_ENCODING =

Returns the :encoding option used for reading when none is given.

Returns:

  • (String) —

    the :encoding option used for reading when none is given

'bom|utf-8'

Class Method Summary collapse

Class Method Details

.decoded_encoding(encoding) ⇒ String

The encoding of strings read with an :encoding option: the internal encoding of 'external:internal', otherwise the external one, without a 'bom|' prefix.

Examples:

CSVUtils::EncodingOptions.decoded_encoding('Windows-1252:UTF-8') # => 'UTF-8'
CSVUtils::EncodingOptions.decoded_encoding('bom|utf-8') # => 'utf-8'

Parameters:

  • encoding (String, Encoding)

Returns:

  • (String)


36
37
38
# File 'lib/csv_utils/encoding_options.rb', line 36

def self.decoded_encoding(encoding)
  encoding.to_s.split(':').last.sub(/\Abom\|/i, '')
end

.read(csv_options) ⇒ Hash

Options for reading: the given options with the default :encoding when they have none.

Parameters:

  • csv_options (Hash)

Returns:

  • (Hash)


18
19
20
# File 'lib/csv_utils/encoding_options.rb', line 18

def self.read(csv_options)
  { encoding: DEFAULT_ENCODING }.merge(csv_options)
end

.write(csv_options) ⇒ Hash

Options for writing values read with csv_options: the :encoding is the one values were decoded to.

Parameters:

  • csv_options (Hash)

Returns:

  • (Hash)


25
26
27
# File 'lib/csv_utils/encoding_options.rb', line 25

def self.write(csv_options)
  csv_options.merge(encoding: decoded_encoding(read(csv_options)[:encoding]))
end