Arduino中国 | Flamingo EDA

Mar/07

14

Rails应用的中文化

在RoR中可以借助gettext来实现应用的本地化(localization),首先确保系统已经安装了gettext(这里使用的是0.16.1版本),然后通过gem安装Ruby-GetText 1.8.0版本:

#gem install gettext

修改RoR工程根目录下的Rakefile文件,加入updatepo和makemo两个任务:

require 'gettext/utils'

desc "Create mo files for L10n"
task :makemo do
  GetText.create_mofiles(true, "po", "locale")
end

desc "Update po files"
task :updatepo do
  MY_APP_TEXT_DOMAIN = "i18n_gettext"
  MY_APP_VERSION = "i18n_gettext 1.0"
  GetText.update_pofiles(MY_APP_TEXT_DOMAIN,
                         Dir.glob("{app,lib}/**/*.{rb,rhtml}"),
                         MY_APP_VERSION)
end

其中updatepo任务的作用是从app和lib目录下的*.rb和*.rhtml文件中提取出以_()标记的字符串,而makemo任务的作用则是根据给定的*.po文件来生成*.mo文件,后者是gettext用来进行中文化处理时所需要的资源文件。
修改app/controllers/application.rb,为RoR应用指定其所使用的语言,它必须和所用的的.po文件名相同。

require 'gettext/rails'

class ApplicationController < ActionController::Base
  init_gettext "i18n_gettext"
  include LoginEngine

  def cookie_lang(lang)
    cookies["lang"] = lang
  end 

  before_filter { |controller|
    controller.cookie_lang("zh")
  }
end

在RoR工程的根目录下创建po/zh目录,然后执行updatepo任务,将应用中所有需要翻译的内容更新到po/i18n_gettext.pot文件中:

# mkdir po/zh -p
# rake updatepo

使用poEdit打开生成的i18n_gettext.pot文件,将其中相应的字符串进行翻译,然后再存为po/zh/i18n_gettext.po。
最后再执行makemo任务 ,将.po文件变成gettext可以理解的.mo文件:

# rake makemo

运行RoR应用,此时就可以在浏览器里看到翻译后的效果了。

No tags

1 comment

  • 老熊的Blog | 老熊的博客 » 哪儿都有TNND的中文问题 · 2007/07/12 at 12:01 AM

    [...] 上周开始看ror,数据库utf8,连接utf8,CRUD操作都没问题, 以为这回终于没啥中文问题了,没想到在ActiveRecord validates又遇到中文问题,默认提示都是E文的,NND,终于出来问题了,有问题问google,参考了1、2、3 在这里把我解决过程记录一下,使用的是ruby gettext。 [...]

Leave a Reply

<<

>>