使用Rails Asset Pipeline在JavaScript文件中编码问题 [英] Encoding issues in javascript files using rails asset pipeline
问题描述
我正在使用Rails 3.1和资产管道(红宝石1.9.2).
I'm using rails 3.1 and the asset pipeline (ruby 1.9.2).
尝试提供具有utf-8编码字符串的javascript js.erb
文件时,出现以下错误
I get the following error when trying to serve a javascript js.erb
file that has utf-8 encoded strings
invalid byte sequence in US-ASCII
我在我的environment.rb文件中设置了Encoding.default_external = "UTF-8"
.如何获得资产管道以其他编码方式投放?
I've set Encoding.default_external = "UTF-8"
in my environment.rb file. How do i get the asset pipeline to serve with a different encoding?
编辑
该错误仅在我在文件外部生成utf-8字符时出现(在这种情况下,通过从数据库查询).如果我添加
The error only shows up when I'm generating the utf-8 character outside of the file (in this case by querying from the DB). The error goes away if I add
<% "日" %>
到文件顶部.我猜这里正在进行某种编码猜测,但是如果没有这种棘手的解决方案,我该如何避免呢?
to the top of the file. I'm guessing there's some kind of encoding guessing going on here, but how do I avoid it without that hacky solution?
推荐答案
在加载文件时,Ruby会尝试猜测"其编码.如果未找到UTF-8或任何其他非ASCII字符,它将使用US-ASCII作为文件编码,如果突然遇到非ASCII字符(例如在运行时加载.
When loading a file, Ruby tries to "guess" its encoding. If no UTF-8 or any other non-ASCII characters are found, it uses US-ASCII as encoding for the file and throws an error if it suddenly encounters a non-ASCII character, which e.g. is loaded at run-time.
此问题的最佳解决方案是通过添加以下命令来强制Ruby使用某种编码
# encoding: utf-8
作为.rb文件的第一行;如果<%# encoding: utf-8 %>
是.erb文件,则为<%# encoding: utf-8 %>
.
The best solution for this problem is to force Ruby to use a certain encoding by adding
# encoding: utf-8
as the first line of a .rb file or <%# encoding: utf-8 %>
if it's a .erb file.
这篇关于使用Rails Asset Pipeline在JavaScript文件中编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!