Module: String::Iconvert

Defined in:
lib/vex/base/string/iconvert.rb

Constant Summary collapse

ALIASES =
{
  "UTF8" => "UTF-8"
}

Class Method Summary collapse

Class Method Details

.char_guessObject



3
4
5
6
7
8
9
10
11
# File 'lib/vex/base/string/iconvert.rb', line 3

def self.char_guess
  @char_guess ||= begin
    require 'charguess' # not necessary if input encoding is known
    CharGuess
  rescue LoadError
    dlog "Please install the charguess gem as pointed out here: http://radiospiel.org/0x2a-smooth-charguess-install"
    FakeCharGuess
  end
end

.convert(s, ie, oe) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/vex/base/string/iconvert.rb', line 18

def self.convert(s, ie, oe)
  invalid_argument! oe unless oe.is_a?(Symbol) or oe.is_a?(String)

  ie ||= char_guess.guess(s)
  return s.dup if ie.nil?
  
  ie, oe = encoding(ie), encoding(oe)
  return s.dup if ie == oe

  #
  # Note: Iconv is part of the ruby std lib.
  require 'iconv'
  Iconv.new(oe, ie).iconv(s)
end

.encoding(enc) ⇒ Object



13
14
15
16
# File 'lib/vex/base/string/iconvert.rb', line 13

def self.encoding(enc)
  enc = enc.to_s.upcase
  ALIASES[enc] || enc
end

.invalid_encoding(*encodings) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/vex/base/string/iconvert.rb', line 37

def self.invalid_encoding(*encodings)
  # Note: "US-ASCII" is always a valid encoding.
  valid = "US-ASCII"

  ex = nil
  invalid_encodings = ([ valid ] + encodings).reject do |enc|
    begin
      Iconv.new(valid, encoding(enc))
    rescue Iconv::InvalidEncoding
      ex = $!
      nil
    end
  end
  
  return if invalid_encodings.empty?
  
  def ex.to_s
    @msg
  end

  ex.instance_variable_set "@msg", 
    "Invalid encoding(s): #{invalid_encodings.join(", ")}; check 'iconv -l' for supported encodings"

  raise ex
end