force_encoding doesn't work well in Chinese charset "gb2312"
Source code in httparty:
def encode_with_ruby_encoding(body, charset)
begin
encoding = Encoding.find(charset)
body.force_encoding(encoding)
rescue
body
end
end
Trying to force_encoding"gb2312":
encode_with_ruby_encoding("\xBD\xF1\xC8\xD5\xBB\xB0\xCC\xE2_\xCC\xDA\xD1\xB6\xCD\xF8", "gb2312")
=> "\x{BDF1}\x{C8D5}\x{BBB0}\x{CCE2}_\x{CCDA}\x{D1B6}\x{CDF8}"
I would like to change force_encoding to encode method:
def encode_with_ruby_encoding(body, charset)
begin
encoding = Encoding.find(charset)
body.encode("utf-8", encoding)
rescue ArgumentError
body
end
end
Then it does indeed work for me:
encode_with_ruby_encoding("\xBD\xF1\xC8\xD5\xBB\xB0\xCC\xE2_\xCC\xDA\xD1\xB6\xCD\xF8", "gb2312")
=> "今日话题_腾讯网"
I do not know much about encoding. Anyone else have any preference on this?
encode_with_ruby_encoding is used to tag the string with the encoding specified in the response headers. We shouldn't actually modify the bytes of the string here, which encode will do.
According to your example, things are working as they should IMO. The reason the string doesn't print properly in your console is because it's probably configured for UTF-8 characters, so Ruby uses an escape sequence to keep the string readable. So when you used encode to transcode it into UTF-8 it gets rendered correctly in your console.
Example of it working my machine:
irb(main):004:0> str = "\xBD\xF1\xC8\xD5\xBB\xB0\xCC\xE2_\xCC\xDA\xD1\xB6\xCD\xF8"
=> "\xBD\xF1\xC8ջ\xB0\xCC\xE2_\xCC\xDAѶ\xCD\xF8"
irb(main):005:0> str.force_encoding('gb2312')
=> "\x{BDF1}\x{C8D5}\x{BBB0}\x{CCE2}_\x{CCDA}\x{D1B6}\x{CDF8}"
irb(main):006:0> puts str
???ջ???_??Ѷ??
=> nil
irb(main):007:0> puts str.encode('UTF-8')
今日话题_腾讯网
I suggest we should leave the force_encoding behavior as-is and hand the string over to the user tagged with the encoding we parsed from the response headers so they can deal with transcoding it into whatever encoding they want it in.
If we were to make the proposed change all body strings would come back as UTF-8. And some users probably don't want that.
If that is indeed what the httparty team wants to do, I'd strongly suggest using Encoding.defaut_internal (which can be nil btw) instead of forcibly using UTF-8.
Awesome. Thanks for the info @brianmario.