- 细小,只用一页程式就为Rails加入l10n支援。
- 简单,它的做法是extend了Object,为它加入新的方法。使用它作l10n很简单,只需要设定了语言,再把原本的字串"blah"改为用 _("blah") 或 (在rhtml中) <%=_ "blah" %> 表达就行了。
- 使用yml储存资料
- 利用route和filter功入动态切换语言的功能
1. 把 i18n.rb 放到 /PROJECT/lib/ 下
- # I18n Module
- # License: http://www.apache.org/licenses/LICENSE-2.0.html
- # URL: http:///articles/2007/02/20/681/
- #
- # Modified from Localization module at mir.aculo.us
- # http://mir.aculo.us/2005/10/03/ruby-on-rails-i18n-revisited
- module I18n
- mattr_accessor :lang
- @@l10s = { :default => {} }
- @@lang = :default
- def self._(string_to_localize, *args)
- translated =
- @@l10s[@@lang][string_to_localize] || string_to_localize
- return translated.call(*args).to_s if translated.is_a? Proc
- translated =
- translated[args[0]>1 ? 1 : 0] if translated.is_a?(Array)
- sprintf translated, *args
- end
- def self.load
- loaded = []
- Dir.glob("#{RAILS_ROOT}/config/lang/*.yml"){ |yml|
- name = File.basename(yml, ".yml")
- translate = YAML.load_file(yml)
- I18n.define(name, translate)
- loaded << name
- }
- return loaded
- end
- def self.define(lang = :default, dictionary = {})
- @@l10s[lang] ||= dictionary
- end
- def self.lang?(lang)
- @@l10s.key?(lang)
- end
- end
- class I18nFilter
- def self.filter(controller)
- usr_lang = controller.request.path_parameters['lang']
- I18n.lang = I18n.lang?(usr_lang) ? usr_lang : :default
- end
- end
- class Object
- def _(*args); I18n._(*args); end
- end
- Rails::Initializer.run do |config|
- # Load Localization
- I18n.load
- end
- # Filters added to this controller will be run for all controllers in the application.
- # Likewise, all the methods added will be available for all controllers.
- class ApplicationController < ActionController::Base
- before_filter I18nFilter
- end
- Show: 显示
- Edit: 修改
- Delete: 移除
- Previous page: 上一页
- Next page: 下一页
- ActionController::Routing::Routes.draw do |map|
- map.connect ':lang/:controller/:action/:id'
- end
- # Call from anywhere (extension to Object class):
- _('blah')
- _('testing %d', 5)
- # in .rhtml
- <%=_ 'testing %d', 1 %>
















