RVM, Ruby 1.9.2, Rails 2.3.8, Passenger and “invalid byte sequence in US-ASCII”

梦想与她 提交于 2019-12-05 09:11:44

Try adding

# encoding: UTF-8
at the top of your main_controller.rb file. If that works, you're dealing with a non US ASCII character in your source file.

In Ruby 1.9, we're dealing with three encoding contexts:

  • Source code encoding: Strings in a source file are interpreted as US-ASCII by default, unless the magic comment I list above is present.
  • External encoding: The characters in a text file are assumed to be in the same encoding as the environment. However one can specify the encoding to use. Eg: open(mydata.txt, "r:UTF-8").
  • Internal encoding: That specifies how the text data is encoded once read from a file. By default this is nil, meaning it will be the same as the encoding used to read it. If something different is needed, it can be specified in IO.open. Eg: open(mydata.txt, 'r:UTF-8:UTF-16LE')

For more info, I'd read James Edward Gray II's great articles on encoding.

I had similar issues on Ubuntu (11.10) because this was in my /etc/apache2/envvars:

## The locale used by some modules like mod_dav
export LANG=C
## Uncomment the following line to use the system default locale instead:
#. /etc/default/locale

Swapping the comments out on this one to use the /etc/default/locale (which contains LANG="en_US.UTF-8") resolved the issue for me without having to make a wrapper for my ruby.

pjmorse

I had a similar issue with a different server, and environment variables turned out to be the culprit.

I agree with pjmorse regarding the environment variable cause, specially in my Passenger/Rails set-up, the culprit was the LANG value.

When starting my Rails app through script/server, I had LANG=en_CA.UTF-8, but not when raising the app with Passenger.

Solution: Modify the Passenger configuration to start Ruby with a wrapper, see http://blog.phusion.nl/2008/12/16/passing-environment-variables-to-ruby-from-phusion-passenger/

Use this as a wrapper:

#!/bin/sh
export LANG=en_CA.UTF-8
exec "/Your_Default_Ruby_Path/ruby" "$@"

Note Your_Default_Ruby_Path is whatever was in the PassengerRuby value of the http.conf before you set-up the wrapper.

Welcome to the wonderful world of forced string encoding; the error is a Ruby 1.9.x vs Ruby 1.8.x behavior difference in strings.

Check http://blog.phusion.nl/2009/02/02/getting-ready-for-ruby-191/ -- might be helpful. You probably just need to update your gemset.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!