Rails国际化(i18n)

来源:互联网 发布:马鞍山市网络大学 编辑:程序博客网 时间:2024/04/29 05:24
很早就知道国际化,就知道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

0 0
原创粉丝点击