Rails 视图编码问题 [英] Rails View Encoding Issues

查看:24
本文介绍了Rails 视图编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Ruby 2.0 和 Rails 3.2.14.我的观点散落着几个 UTF-8 字符,主要是货币符号,如 บาท 和 د.إ 等.我注意到一些

I'm using Ruby 2.0 and Rails 3.2.14. My view is littered several UTF-8 characters, mainly currency symbols like บาท and د.إ etc. I noticed some

(ActionView::Template::Error) "incompatible character encodings: ASCII-8BIT and UTF-8

在我们的生产代码中,并立即尝试在我的浏览器上访问页面 URL,没有任何问题.深入研究后,我意识到错误实际上是由 BingBot 和少数蜘蛛引起的.因此,当我尝试卷曲相同的 url 时,我能够重现该问题.所以,如果我尝试

in our production code and promptly tried visiting the page url on my browser without any issues. On digging in, I realised the error was actually caused by BingBot and few spiders. So when I tried to curl the same url, I was able to reproduce the issue. So, if I try

curl http://localhost:3000/?x=✓

我收到错误,其中在视图代码中使用了 UTF-8 符号.我还意识到,如果使用 HTML 编码的字符串代替符号,则不会发生这种情况.不过,我更喜欢使用实际符号.

I get the error where UTF-8 symbols are used in the view code. I also realised that if use HTML encoded strings in place of the symbols, this does not occur. However, I prefer using the actual symbols.

而且我已经尝试在 environment.rb 中设置 Encoding.default_external = Encoding::UTF_8 将 #encoding: utf-8 魔术注释添加到文件顶部,但没有帮助.

And I have already tried setting Encoding.default_external = Encoding::UTF_8 in environment.rb adding #encoding: utf-8 magic comment to top of file and it does not help.

那么,为什么会出现这个错误呢?除了 cookie 之外,在浏览器和 CURL 上点击这个 url 有什么区别?我该如何解决此问题并允许 BingBot 为我们的网站编制索引?谢谢.

So, why does this error occur? What is the difference between hitting this url on browser and on CURL besides cookies? And how do I go about fixing this issue and allow BingBot to index our site? Thanks.

推荐答案

在我的模板中泄露非 UTF-8 字符的罪魁祸首是 Facebook Open Graph 的一个无害元标记

The culprit that was leaking non UTF-8 characters in my template was an innocuous meta tag for Facebook Open Graph

%meta{property: "og:url", content: request.url}

当请求是非标准的时,这会导致编码问题.改成

And when the request is non-standard, this causes the encoding issue. Changing it to

%meta{property: "og:url", content: request.url.force_encoding('UTF-8')}

成功了.

这篇关于Rails 视图编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆