結合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源文件里輸入中文了。
posted on 2006-10-12 15:44
壞男孩 閱讀(895)
評論(1) 編輯 收藏 所屬分類:
新知識學習