27

I can specify any ruby file to use specific encoding by add a comment line at its top:

#encoding: utf-8

But in Rails' config/application.rb, I found this:

config.encoding = "utf-8"

Are they different? If I have set config.encoding = "utf-8", still I need #encoding: utf-8?

Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164

1 Answers1

42

The config.encoding = "utf-8" part in config/application.rb is related to how rails should interpret content.

#encoding: utf-8 in a ruby file tells ruby that this file contains non-ascii characters.

These two cases are different. The first one (in config/application.rb) tells rails something, and has nothing at all to do with how ruby itself should interpret source files.

You can set the environment variable RUBYOPT=-Ku if you're lazy and want ruby to automatically set the default file encoding of .rb files to utf-8, but I'd rather recommend that you put your non-ascii bits in a translation file and reference that with I18n.t.

Frost
  • 11,121
  • 3
  • 37
  • 44
  • `how rails should interpret content`? Could you give an example? – Lai Yu-Hsuan Oct 08 '11 at 20:16
  • This is related to what encoding rails should use when talking to the database, or retrieving data from a form, for instance. – Frost Oct 08 '11 at 20:21
  • 12
    Actually `#encoding: utf-8` tells ruby to *interpret* the source of the file as `utf-8`, even if it doesn't contain any non-ascii characters. ;) – Ion Br. Oct 08 '11 at 20:28
  • What if the variable data itself has an accented character? (é). For example, in my Cucumber tests, I'm required to use accented characters to test against my repo. But Rails won't let me print these types of characters. – Trip Aug 16 '13 at 20:23
  • @Trip In that case, you'll need to have `#encoding: utf-8` in your cucumber tests. The ruby scripts themselves will still be able to handle unicode characters, such as accented characters. – Frost Feb 17 '14 at 19:32
  • 8
    This whole `#encoding: utf-8` business is only an issue when using ruby versions prior to 2.0.0. As of 2.0.0, ruby now defaults to interpret source files as utf-8. – Frost Feb 17 '14 at 19:35