Ruby:如何添加“#encoding: UTF-8”自动地?
有没有什么gem可以自动将#encoding: UTF-8
添加到每个Ruby文件中?
或者是否有其他方法可以防止整个 Ruby on Rails 项目(不仅仅在单个类中)出现 invalid multibyte char (US-ASCII)
错误?
Is there any gem which adds # encoding: UTF-8
to each Ruby file automatically?
Or is there any other way to prevent from the invalid multibyte char (US-ASCII)
error in the entire Ruby on Rails project (not in a single class only)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
升级到 Ruby 2.0,因为它将 UTF-8 设为默认编码,从而不再需要魔法注释。
Upgrade to Ruby 2.0, as it makes UTF-8 the default encoding, removing the need for magic comments.
尝试 magic_encoding gem,它可以将 uft-8 魔法注释插入到您应用中的所有 ruby 文件中。
[编辑]
现在切换到 SublimeText 我使用 auto-encoding-for-ruby 插件。
Try magic_encoding gem, it can insert uft-8 magic comment to all ruby files in your app.
[EDIT]
Having switched to SublimeText now I use auto-encoding-for-ruby plugin.
维姆:
Vim:
如果您使用的是 Sublime Text 2,则可以使用一个在需要时自动包含编码声明的插件: https://github.com/elomarns/auto-encoding-for-ruby。
If you're using Sublime Text 2, you can use a plugin that automatically includes encoding declaration when needed: https://github.com/elomarns/auto-encoding-for-ruby.
只运行一个脚本怎么样?
为了让它自动添加到你的 Rakefile 中。
如果您只想更新具有 utf-8 字符的文件,可以运行
file -bi #{path}
并查找 charset=utf-8。How about just running a script?
To make it automatic add this to your Rakefile.
You could run
file -bi #{path}
and look for charset=utf-8 if you only want to update files that have utf-8 chars.只有当您的文件真正以 UTF-8 存储时,自动向每个 Ruby 文件添加
#encoding: UTF-8
才有意义。如果您的文件采用 CP850 编码(据我所知,Windows 中的默认值)并且您使用非 ASCII 字符,则可以将
无效的多字节字符 (US-ASCII)
替换为无效的多字节字符 (UTF-8)< /代码>。
我更喜欢手动修改和检查每个文件(如果它确实是 UTF-8)。
Adding a
# encoding: UTF-8
to each Ruby file automatically makes only sense, when your files are really stored in UTF-8.If your files are encoded CP850 (AFAIK default in Windows) and you use Non-ASCII characters, you replace
invalid multibyte char (US-ASCII)
withinvalid multibyte char (UTF-8)
.I would prefer a manual modification and check of each file, if it is really UTF-8.