RoR ASCII-8bit إلى UTF-8 مع رموز غير لاتينية (سيريلية) في Net::HTTP.get_response.body
-
13-12-2019 - |
سؤال
أحتاج إلى الحصول على بعض البيانات عبر Net::HTTP، فهو يعمل بشكل جيد من خلال تلقي الاستجابة بتنسيق ASCII-8bit.المشكلة هي كيفية تشفير هذا إلى utf8 وحفظ جميع الرموز غير اللاتينية؟
مع @content.encode('utf-8', 'binary', :invalid => :replace,
:undef => :replace, :replace => '')
لقد فقدت كل الرموز السيريلية
مع @content.encode('utf-8', 'binary')
انا حصلت "\xCB" from ASCII-8BIT to UTF-8
خطأ
مع @content.force_encoding("UTF-8)
أحصل على ��������� بدلا من الرموز السيريلية
لا أستطيع العثور على إجابة مع بحث جوجل.
المحلول
تم حل المشكلة مع
begin
cleaned = response.body.dup.force_encoding('UTF-8')
unless cleaned.valid_encoding?
cleaned = response.body.encode( 'UTF-8', 'Windows-1251' )
end
content = cleaned
rescue EncodingError
content.encode!( 'UTF-8', invalid: :replace, undef: :replace )
end
لا تنتمي إلى StackOverflow