Rails國際化(i18n)

很早就知道國際化,就知道i18n,卻不知道是什麼原因。原來internationalization(國際化),這個單詞的長度是20,然後取其首尾字母,中間省略的字母剛好18個。 

選用了Locale作爲國際化的解決方案。 
1、首先是安裝 
Shell代碼  收藏代碼
  1. gem install locale_rails  

會自動的安裝locale和locale_rails兩個gem。 

2、生成i18n的配置文件 
Ruby代碼  收藏代碼
  1. # in config/initializer/locale.rb  
  2.   
  3. # Tell the I18n library where to find your translations  
  4. I18n.load_path += DirFile.join(RAILS_ROOT, 'lib''locale''*.{rb,yml}') ]  
  5.   
  6. # Tell the supported locales. This is the one of additional setting by Ruby-Locale for Ruby on Rails.  
  7. # If supported_locales is not set, the locale information which is given by WWW browser is used.  
  8. # This setting is required if your application wants to restrict the locales.  
  9. I18n.supported_locales = DirFile.join(RAILS_ROOT, 'lib''locale''*.{rb,yml}') ].collect{|v| File.basename(v, ".*")}.uniq  
  10.   
  11. # Tell the default locale. If this value is not set, "en" is set.  
  12. # With this library, this value is used as the lowest priority locale  
  13. # (If other locale candidates are not found, this value is used).  
  14. I18n.default_locale = "en-US"   


3、gem的引用 
Ruby代碼  收藏代碼
  1. # config/environment.rb  
  2. Rails::Initializer.run do |config|  
  3.  :  
  4.  :  
  5.  config.gem 'locale'  
  6.  config.gem 'locale_rails'  
  7. end  

app/controllers/application.rb中不需要定義set_locale。 

4、基本知識 
Ruby代碼  收藏代碼
  1. I18n.translate "hello"  
  2. I18n.localize Time.now  
  3. # 簡寫  
  4. I18n.t "hello"  
  5. I18n.l Time.now  

多國語文件默認的放在config/localese文件夾下,假設你要支持中文和英語,那麼你需要在這個文件夾下放置en.yml和zh.yml。 
Yml代碼  收藏代碼
  1. # zh-CN.yml  
  2. "zh-CN":  
  3.   submit: '提交'  
  4.   create: '創建'  
  5. #en.yml  
  6. en:  
  7.   submit: 'Submit'  
  8.   create: 'Create'  

試圖中更加簡單,你可以直接調用t方法: 
Ruby代碼  收藏代碼
  1. <%= t 'submit' %>  


5、使用 
你可以進入Console進行測試: 
引用
> I18n.t 'submit' 
=> "Submit" 
> I18n.locale = 'zh' 
=> "zh" 
> I18n.t('submit') 
=> "提交"


6、傳遞變量 
有些時候,我們的字符串中可能需要包含變量,只需要將其放在兩個大括號內就可以了: 
Yml代碼  收藏代碼
  1. # zh-CN.yml  
  2. "zh-CN":  
  3.   hello: "你好, {{name}}"  

打開console: 
引用
> I18n.t 'hello', :name => 'Rails' 
=> "你好,Rails!"


還可以進行單複數處理、時間和日期本地化、貨幣處理、ActiveRecord和route處理。 

解決問題 
1、undefined method set_app_language_tags錯誤 
引用
c:/ruby/lib/ruby/gems/1.8/gems/locale_rails-2.0.5/lib/locale_rails/i18n.rb:28:in `supported_locales=': undefined method `set_app_language_tags' for I18n::Locale:Module (NoMethodError)

方法:http://github.com/mutoh/locale_rails/issues/#issue/2 

2、translation_missing錯誤 
千萬要記住日文是ja,簡體中文是zh-CN,爲了這個鬱悶了好久 

參考: 
http://guides.rubyonrails.org/i18n.html 
http://github.com/svenfuchs/rails-i18n (多國語文件) 
http://www.yotabanana.com/hiki/ruby-locale-rails-howto.html 
http://www.letrails.cn/archives/rails-2-2-i18n-tutorials/ 

http://d.hatena.ne.jp/willnet/20100430/1272618929

轉載地址:http://ilgnep.iteye.com/blog/686353

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章