Ruby本身不支持UTF-8但是我们可以使用些办法使用8bit来储存UTF-8编码后串.但是这会导致些串出现问题可以通过使用jcode包里来替换原来串如length可以用jlength替换
1、首先我们需要在public/dispatch.cgi文件#!/path/to/ruby后面加上-Ku -rjcode
2、然后需要使用个before_filter来输出http头表示使用utf-8集
ApplicationController < ActionController::Base
before_filter :_char
def _char
@headers["Content-Type"] = "text/html; char=utf-8"
end
end
3、接着如果要在Safari浏览器里使用railsajax帮助则必须加入以下代码
ApplicationController < ActionController::Base
after_filter :fix_unicode_for_safari
# automatically and transparently fiixes utf-8 bug
# with Safari when using xmlhttp
def fix_unicode_for_safari
@headers["Content-Type"] "text/html; char=utf-8" and
@request.env['HTTP_USER_AGENT'].to_s.? 'AppleWebKit' then
@response.body = @response.body.gsub(/([^x00-xa0])/u) { |s| "&#x%x;" % $1.unpack('U')[0] }
end
end
4、另外可能需要调整数据库设置能够存储utf-8串
5、必须把rb源文件以及rhtml等模版文件都保存为utf-8格式
这样你就可以直接在rb源文件里输入中文了
最新评论