Encoding issues in javascript files using rails asset pipeline

主宰稳场 提交于 2019-12-01 00:14:19

问题


I'm using rails 3.1 and the asset pipeline (ruby 1.9.2).

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

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?

EDIT

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/7761540/encoding-issues-in-javascript-files-using-rails-asset-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!