Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid putting the magic encoding comment on top of every UTF-8 file in Ruby 1.9?

I have a Rails project with a lot of Cyrillic strings in it.

It worked fine on Ruby 1.8, but Ruby 1.9 assumes source files are US-ASCII-encoded unless you provide an # encoding: utf-8 comment at the top of the source file. At that point the files are not considered US-ASCII.

Is there a simpler way to tell Ruby "This application is UTF8-encoded. Please consider all and any included source files as UTF8 unless declared otherwise"?


UPDATE:

I wrote "How to insert the encoding: UTF-8 directive automatically in Ruby 1.9 files" which appends the encoding directive automatically if it's needed.

like image 280
Leonid Shevtsov Avatar asked Jul 20 '10 14:07

Leonid Shevtsov


People also ask

Is UTF-8 the default encoding?

Show activity on this post. The way I read the spec, UTF-8 is not the default encoding in an XML declaration. It is only the default encoding "for an entity which begins with neither a Byte Order Mark nor an encoding declaration".

What is encoding =' UTF-8?

UTF-8 is an encoding system for Unicode. It can translate any Unicode character to a matching unique binary string, and can also translate the binary string back to a Unicode character. This is the meaning of “UTF”, or “Unicode Transformation Format.”


2 Answers

I think you can either

  1. use -E utf-8 command line argument to ruby, or
  2. set your RUBYOPT environment variable to "-E utf-8"
like image 81
Mladen Jablanović Avatar answered Sep 18 '22 19:09

Mladen Jablanović


In my opinion, explicit is not always better than implicit.

When almost all the source you use is UTF-8 compatible, you can easily avoid putting the magic encoding comment by using Ruby's -Ku command-line options.

Don't confuse the "u" parameter of the -K options with -U options.

-Ku : set internal and script encoding to utf-8 -U  : set internal encoding to utf-8 

Then, set the magic encoding comment only in scripts that need it. Remember, convention over configuration!

You can set the environment variable RUBYOPT=-Ku

See Ruby's command-line options at http://www.manpagez.com/man/1/ruby/.

like image 45
Totor Avatar answered Sep 21 '22 19:09

Totor