Module: Git::EncodingUtils

Defined in:
lib/git/encoding_utils.rb

Overview

Method that can be used to detect and normalize string encoding

Class Method Summary collapse

Class Method Details

.best_guess_encoding



12
13
14
15
# File 'lib/git/encoding_utils.rb', line 12

def self.best_guess_encoding
  # Encoding::ASCII_8BIT.name
  Encoding::UTF_8.name
end

.default_encoding



8
9
10
# File 'lib/git/encoding_utils.rb', line 8

def self.default_encoding
  __ENCODING__.name
end

.detected_encoding(str)



17
18
19
# File 'lib/git/encoding_utils.rb', line 17

def self.detected_encoding(str)
  CharDet.detect(str)['encoding'] || best_guess_encoding
end

.encoding_options



21
22
23
# File 'lib/git/encoding_utils.rb', line 21

def self.encoding_options
  { invalid: :replace, undef: :replace }
end

.normalize_encoding(str)



25
26
27
28
29
30
31
# File 'lib/git/encoding_utils.rb', line 25

def self.normalize_encoding(str)
  return str if str.valid_encoding? && str.encoding.name == default_encoding

  return str.encode(default_encoding, str.encoding, **encoding_options) if str.valid_encoding?

  str.encode(default_encoding, detected_encoding(str), **encoding_options)
end