Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/string/utf8.rb

Overview

This monkey patch add ability of turning stirng’s encoding into utf8

Example:

require 'string/utf8'
p "\xD6\xD0\xCE\xC4".utf8!
=> "中文"

Constant Summary collapse

ENCODINGS =
%w(ascii-8bit utf-8 ucs-bom shift-jis gb18030 gbk gb2312 cp936)

Instance Method Summary collapse

Instance Method Details

#utf8!Object

for ruby1.9+



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/string/utf8.rb', line 32

def utf8!
  ENCODINGS.any? do |c|
    begin
      self.encode!('utf-8', c).force_encoding('utf-8')
      if self.valid_encoding?
        $enc = c
        true
      end
    rescue
    end
  end
  self
end