Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global settings to solve invalid multibyte char (US-ASCII) in Rails 3

My problem is simillar to Rails 3 invalid multibyte char (US-ASCII)

Solution, presented there does works, but i find this a little goofy to include comment # encoding: UTF-8 to every file, that uses non ASCII characters.

In config/application.rb, i have following option:

# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"

But, it does't helps.

Maybe, some another global configuration option is presented exactly for such cases ?

like image 335
AntonAL Avatar asked Apr 27 '11 19:04

AntonAL


2 Answers

There is no way to default Ruby 1.9 to use UTF-8 for all source files (and yes, it's a huge PITA).

The config.encoding setting is telling Rails something, nothing to do with Ruby.

The best solution I've come up with relies on something that I haven't seen mentioned. There's another way to get Ruby 1.9 to see a file as UTF-8, instad of using that magic comment you can include the UTF-8 BOM (Byte Order Marker) in your file. Ruby 1.9 will do the right thing.

Now to the cool part - I use gvim, and it's actually very simple to configure gvim to put a BOM into every file that should have one. It's as simple as adding this to my .vimrc:

set bomb

Not sure if you're using gvim, or if other editors can do this. So obviously YMMV :)

like image 73
smathy Avatar answered Oct 19 '22 19:10

smathy


You can set the environment variable RUBYOPT=-Ku when running the application, and it will make ruby (even 1.9) assume utf-8 encoding for all .rb source files.

For a rails app though, I would rather recommend not using that trick, and instead put your non-ascii parts in the i18n files and referencing them through I18n.t.

It's a bit more tedious to set up if you've already got your application up and running, but should you ever need to translate it into another language you're already halfway there.

like image 40
Frost Avatar answered Oct 19 '22 20:10

Frost