简体   繁体   English

Ruby 中单引号的 UTF-8 中的无效字节序列

[英]invalid byte sequence in UTF-8 for single quote in Ruby

I'm using the following code to show description in template:我正在使用以下代码在模板中显示描述:

json.description resource.description if resource.description.present?

It gives me invalid byte sequence in UTF-8 error.它在 UTF-8 错误中给了我无效的字节序列。 I dig this a little bit, and find out the issue is my description has single quote as ' instead of '.我稍微挖掘了一下,发现问题是我的描述将单引号作为'而不是'。 Wondering what's the best way to fix this encoding issue?想知道解决此编码问题的最佳方法是什么? Description is input by user and I have no control over it.描述由用户输入,我无法控制。 Another weird issue is, I have multiple test environments, they all have the same Ruby and Rails version and they are running the same code, but only one of the environment has this error.另一个奇怪的问题是,我有多个测试环境,它们都具有相同的 Ruby 和 Rails 版本并且运行相同的代码,但只有一个环境出现此错误。

def to_utf8(str)
  str = str.force_encoding("UTF-8")
  return str if str.valid_encoding?
  str = str.force_encoding("BINARY")
  str.encode("UTF-8", invalid: :replace, undef: :replace)
end

ref: https://stackoverflow.com/a/17028706/455770参考: https : //stackoverflow.com/a/17028706/455770

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ruby on Rails在UTF-8中的无效字节序列 - Ruby on Rails invalid byte sequence in UTF-8 UTF-8中的Ruby on Rails无效字节序列(ArgumentError) - Ruby on Rails invalid byte sequence in UTF-8 (ArgumentError) 由于机器人,Ruby on Rails“UTF-8 中的字节序列无效” - Ruby on Rails “invalid byte sequence in UTF-8” due to bot 有没有办法清除 Ruby 中“UTF-8 中的无效字节序列”错误的文件? - Is there a way to clean a file of “invalid byte sequence in UTF-8” errors in Ruby? Ruby'to_json'抛出ArgumentError:UTF-8中无效的字节序列 - Ruby 'to_json' throws ArgumentError: invalid byte sequence in UTF-8 Ruby / Nokogiri网站抓取-UTF-8中的无效字节序列(ArgumentError) - Ruby/Nokogiri site scraping - invalid byte sequence in UTF-8 (ArgumentError) Ruby 2.1.5-ArgumentError:UTF-8中的无效字节序列 - Ruby 2.1.5 - ArgumentError: invalid byte sequence in UTF-8 Ruby / Rails CSV解析,UTF-8中的无效字节序列 - Ruby/Rails CSV parsing, invalid byte sequence in UTF-8 Ruby on Rails 问题:在“匹配?”中:UTF-8(ArgumentError)中的字节序列无效? - Ruby on Rails problem: in `match?': invalid byte sequence in UTF-8 (ArgumentError)? Ruby on Rails - 来自Paypal的params:utf-8中的无效字节序列 - Ruby on Rails - params from Paypal : invalid byte sequence in utf-8
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM