Class: ANSEL::Convert

Inherits:
Object
  • Object
show all
Includes:
CharacterMap
Defined in:
lib/ansel_iconv/converter.rb

Instance Method Summary collapse

Constructor Details

#initialize(to_charset = 'UTF-8') ⇒ Convert


7
8
9
# File 'lib/ansel_iconv/converter.rb', line 7

def initialize(to_charset = 'UTF-8')
  @to_charset = to_charset
end

Instance Method Details

#ansi_to_utf8Object


11
12
13
# File 'lib/ansel_iconv/converter.rb', line 11

def ansi_to_utf8
  @ansi_to_utf8 ||= @@non_combining.merge(@@combining)
end

#iconv(string) ⇒ Object


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ansel_iconv/converter.rb', line 15

def iconv(string)
  output = ''
  scanner = StringScanner.new(string)
  until scanner.eos? do
    byte = scanner.get_byte
    char = byte.unpack('C')[0]

    if char <= 0x7F
      output << byte
    elsif char >= 0x88 && char <= 0xC8
      hex_key = char.to_s(16).upcase
      output << ::Iconv.conv(@to_charset, 'UTF-16', ansi_to_utf8[hex_key] || ansi_to_utf8['ERR'])
      scanner.get_byte # ignore the next byte
    elsif char >= 0xE0 && char <= 0xFB
      [2, 1, 0].each do |n| # try 3 bytes, then 2 bytes, then 1 byte
        bytes = [char.to_s(16).upcase]
        scanner.peek(n).each_byte {|b| bytes << b.to_s(16).upcase}
        hex_key = bytes.join('+')
        if ansi_to_utf8.has_key?(hex_key)  
          output << ::Iconv.conv(@to_charset, 'UTF-16', ansi_to_utf8[hex_key])
          n.times {scanner.get_byte}
          break
        end
      end
    else
      output << ::Iconv.conv(@to_charset, 'UTF-16', ansi_to_utf8['ERR'])
      scanner.get_byte if scanner.get_byte.unpack('C')[0] >= 0xE0 # ignore the next byte
    end
  end
  
  @to_charset == 'UTF-8' ? output : ::Iconv.conv(@to_charset, 'UTF-8', output)
end