Created
February 1, 2012 07:52
-
-
Save qhwa/1715847 to your computer and use it in GitHub Desktop.
turn string encoding into utf-8 from any charset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class String | |
| def utf8! | |
| %w(ascii-8bit utf-8 ucs-bom shift-jis gb18030 gbk gb2312 cp936).any? do |c| | |
| begin | |
| if self.respond_to? :encode | |
| self.encode!('utf-8', c).force_encoding('utf-8') | |
| else | |
| require 'iconv' | |
| text = Iconv.new('UTF-8', c).iconv(self) | |
| end | |
| if self =~ /./ | |
| $enc = c | |
| return self | |
| end | |
| rescue | |
| end | |
| end | |
| self | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment