class UTF8Converter

Class used to keep the default common encoding and the helper methods for the string conversion

This partial class defines the version of the gem

Constants

DEFAULT_COMMON_ENCODINGS
DEFAULT_REPLACE_CHARACTER
VERSION

Attributes

common_encodings[RW]
default_replace_character[RW]

Public Class Methods

convert_to_utf8!(string) click to toggle source
# File lib/utf8_converter.rb, line 31
def self.convert_to_utf8!(string)
  if string.force_encoding(Encoding::UTF_8).valid_encoding?
    return string.encode!(Encoding::UTF_8)
  end
  @common_encodings.each do |encoding|
    return string if try_convert_from_encoding_to_utf8!(string, encoding)
  end
  string.encode!(Encoding::UTF_8, 
                 invalid: :replace, 
                 undef: :replace, 
                 replace: @default_replace_character)
end
try_convert_from_encoding_to_utf8!(string, encoding) click to toggle source
# File lib/utf8_converter.rb, line 20
def self.try_convert_from_encoding_to_utf8!(string, encoding)
  original_encoding = string.encoding
  begin
    string.force_encoding(encoding).encode!(Encoding::UTF_8)
    true
  rescue
    string.force_encoding(original_encoding)
    false
  end
end