rails 本地化i18n

基础配置
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += %W(#{config.root}/lib/bootstrap)
config.i18n.locale = 'zh-CN'
config.i18n.default_locale = 'zh-CN'
上面配置之后其它不管文件名取为devise.zh-CN.yml还是simple_form.zh_CN.yml只要里面文件第一句为zh-CN:那么就会对应本地化。
产生两个方法i18n.t/l
单独读取本地化时采用上面的方法,然后层层剥去里面的结构
I18n.t("models." + model.to_s.underscore) 如果有多层则在到参数地方按照结构的层次往下加I18n.t("datatime."+'user.'+'name')这样达到目的

项目做的一个获取所有模型对应的本地化。
(1)使用ActiveRecord::Base.descendants获取所有模型名字
     在lib文件下创建一个all_models.rb
     # -*- encoding : utf-8 -*-
module Rails
  def self.all_models
    Rails.application.eager_load! if Rails.env != "production" rescue nil
    ActiveRecord::Base.descendants
  end
end
(2)创建所有模型本地化的实例,在前端直接使用
require './lib/all_models'
before_filter :get_all_models, only: [:new, :edit]
private
  def get_all_models
    @all_models = Rails.all_models.map do |model|
      translation = I18n.t("models." + model.to_s.underscore)
      if translation.include? 'translation missing'
        nil
      else
        [translation,model.to_s]
      end
    end.compact.sort
  end
<td><%= f.input :subject_class, collection: @all_models, label: false, :include_blank => "请选择", :input_html => {:class => "select2"} %></td>

使用yml文件进行初始化数据。
读取文件内容方式YAML.load_file("#{Rails.root}/config/database.yml")
读到的是一个hash。可以作为参数直接传给某个模型。这样就完成了创建。

猜你喜欢

转载自hhg08.iteye.com/blog/2222054