Class: UTF8Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/utf8_converter.rb,
lib/utf8_converter/version.rb

Overview

This partial class defines the version of the gem

Constant Summary collapse

DEFAULT_COMMON_ENCODINGS =
[
  Encoding::ISO_8859_1, 
  Encoding::Windows_1252
]
DEFAULT_REPLACE_CHARACTER =
'?'
VERSION =
'0.1.1'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.common_encodingsObject

Returns the value of attribute common_encodings.



13
14
15
# File 'lib/utf8_converter.rb', line 13

def common_encodings
  @common_encodings
end

.default_replace_characterObject

Returns the value of attribute default_replace_character.



14
15
16
# File 'lib/utf8_converter.rb', line 14

def default_replace_character
  @default_replace_character
end

Class Method Details

.convert_to_utf8!(string) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# 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) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# 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