`

在RubyOnRails里使用UTF-8及中文字符串

阅读更多
结合RubyOnRails官方Wiki上的一些介绍和自己实践写的。这个方法就是在使用rails的内置的长度校验的时候要考虑到中文一般占用3个字符。

Ruby本身不支持UTF-8,但是我们可以使用一些办法使用8bit的字符来储存UTF-8编码后的字符串.但是这会导致一些字符串函数出现问题,可以通过使用jcode包里的函数来替换原来的字符串函数,如length可以用jlength替换。
1、首先,我们需要在public/dispatch.cgi文件的#!/path/to/ruby后面加上-Ku -rjcode
2、然后,需要使用一个before_filter来输出http头,表示使用utf-8字符集。
class ApplicationController < ActionController::Base
before_filter :set_charset

def set_charset
@headers["Content-Type"] = "text/html; charset=utf-8"
end
end
3、接着,如果要在Safari浏览器里使用rails的ajax帮助函数,则必须加入以下代码
class 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
if @headers["Content-Type"] == "text/html; charset=utf-8" and
@request.env['HTTP_USER_AGENT'].to_s.include? '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源文件里输入中文了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics