August 25,2006

Rails 上面 Error Message 中文化

Rails 有一點設計的不夠完善
就是 i18n 的問題
當然這個問題可以用 gettext 去解決
不過 , 如果有更簡單的方式 , 也是不錯的
到目前為止
Model 裡面的 Validate Error 目前是官方無解的
所以我就從 Rails Wiki 裡面找出了不錯的解法
第一個連結
第二個連結

老師有說過
好的設計帶你上天堂, 不好的設計帶你住套房
Rails 以 Ruby 當作中心語言雖然沒有到上天堂的程度
但是 Ruby 的 Open Class 的特性
卻讓這個解法不需要動用到Rails目錄裡面去修改 Source Code
可說是相當有趣的解法

寫下列的程式在 你的 app 目錄下面

# active_record/errors.rb

module ActiveRecord
class Errors
begin
@@default_error_messages.update( {
:inclusion => "中文",
:exclusion => "中文",
:invalid => "中文",
:confirmation => "中文",
:accepted => "中文",
:empty => "中文",
:blank => "中文",
:too_long => "中文",
:too_short => "中文",
:wrong_length => "中文",
:taken => "中文",
:not_a_number => "中文",
})
end
end
end


然後,
在 config/enviorment.rb 加入

require "#{RAILS_ROOT}/app/你的filename"


這樣就可以把 error message 內容變成 中文
如果要上面的框框都變成中文
在剛剛那個 filename 加入


module ActionView #nodoc
module Helpers
module ActiveRecordHelper
def error_messages_for(object_name, options = {})
options = options.symbolize_keys
object = instance_variable_get("@#{object_name}")
unless object.errors.empty?
content_tag("div",
content_tag(
options[:header_tag] || "h2",

"一共有 #{pluralize(object.errors.count, "error")} 問>題 "
) +
content_tag("p", "請更正:") +
content_tag("ul", object.errors.full_messages.collect { |msg| content_tag("li", msg) }),
"id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
)
end
end
end
end


成品如下圖


題外化
select_month 的英文也可以靠這個變成中文

# date.rb

require 'date'

class Date
MONTHNAMES = [nil, '一月', '二月', '三月', '四月', '五月',
'六月', '七月', '八月', '九月', '十月',
'十一月', '十二月' ]
end

Posted by thegiive at 樂多Roodo! │20:04 │回應(0)引用(0)Ruby and Rails
樂多分類:網路/3C 工具:編輯本文
Ads by Roodo! 

引用URL

http://cgi.blog.roodo.com/trackback/2064413