很早就知道国际化,就知道i18n,却不知道是什么原因。原来internationalization(国际化),这个单词的长度是20,然后取其首尾字母,中间省略的字母刚好18个。
选用了Locale作为国际化的解决方案。
1、首先是安装
gem install locale_rails
会自动的安装locale和locale_rails两个gem。
2、生成i18n的配置文件
# in config/initializer/locale.rb
# Tell the I18n library where to find your translations
I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
# Tell the supported locales. This is the one of additional setting by Ruby-Locale for Ruby on Rails.
# If supported_locales is not set, the locale information which is given by WWW browser is used.
# This setting is required if your application wants to restrict the locales.
I18n.supported_locales = Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ].collect{|v| File.basename(v, ".*")}.uniq
# Tell the default locale. If this value is not set, "en" is set.
# With this library, this value is used as the lowest priority locale
# (If other locale candidates are not found, this value is used).
I18n.default_locale = "en-US"
3、gem的引用
# config/environment.rb
Rails::Initializer.run do |config|
:
:
config.gem 'locale'
config.gem 'locale_rails'
end
app/controllers/application.rb中不需要定义set_locale。
4、基本知识
I18n.translate "hello"
I18n.localize Time.now
# 简写
I18n.t "hello"
I18n.l Time.now
多国语文件默认的放在config/localese文件夹下,假设你要支持中文和英语,那么你需要在这个文件夹下放置en.yml和zh.yml。
# zh-CN.yml
"zh-CN":
submit: '提交'
create: '创建'
#en.yml
en:
submit: 'Submit'
create: 'Create'
试图中更加简单,你可以直接调用t方法:
<%= t 'submit' %>
5、使用
你可以进入Console进行测试:
引用
> I18n.t 'submit'
=> "Submit"
> I18n.locale = 'zh'
=> "zh"
> I18n.t('submit')
=> "提交"
6、传递变量
有些时候,我们的字符串中可能需要包含变量,只需要将其放在两个大括号内就可以了:
# zh-CN.yml
"zh-CN":
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