views:

316

answers:

2

I have an Rails application with SayController, hello action and view template say/hello.html.erb. When I add some cyrillic character like "ю", I get an error:

ArgumentError in SayController#hello

invalid byte sequence in UTF-8

Headers:

{"Cache-Control"=>"no-cache",
 "X-Runtime"=>"11",
 "Content-Type"=>"text/html; charset=utf-8"}

If I try to write this letter with embedded Ruby,

<%= "ю" %>

I don't get any error, but it displays a question mark in black square (�) instead of this letter.

I use Windows 7 x64, Ruby 1.9.1p378, Rails 2.3.5, WEBrick server.

+1  A: 

A likely cause of this error is that the file which contains the cyrillic letters is not encoded in UTF8, but perhaps in some russian encoding like KOI8. This will cause the characters to be impossible to interpret in UTF8 (and rightly so!).

So double check that your file is properly encoded in UTF8.

Olivier
Thank you, double checking helped :-) I thought I have setted UTF-8 as default encoding for project in IDE preferenses...
Semyon Perepelitsa
A: 

Create a initializer file (e.g encoding_fix.rb) under your_app/config/initializers with the following content:

Encoding.default_internal = Encoding::UTF_8 if RUBY_VERSION > "1.9"
Encoding.default_external = Encoding::UTF_8 if RUBY_VERSION > "1.9"

This sets the encoding to utf8.

phil
I've done exactly what you say, but still getting the same error. As you can see in "Headers" section, the server is sending data in UTF-8.
Semyon Perepelitsa
This does not work.
epochwolf
My code snippet converts ruby strings, i.e strings inside erb tags to the encoding. Characters outside of erb tags are interpreted with the file's actual encoding.
phil