2.0でRuby-GetTextを使う

Ruby-GetTextの設定もRails2.0.2環境用に変更しておく必要があった。

  • rails2.0.2のscript/consoleで確認すると、デフォルト設定がUTF-8*1だった。$KCODE = 'u'は、コメントアウトしておいた。コメントアウトしないで、そのまま残しても良いと思う。)もし、任意の文字コード指定をするなら、Rails::Initializer.runブロックの直後に行うのが良さそう。
# config/environment.rb

# 文字コードの設定。(Rails1.2以降の文字コードの指定はRails::Initializer.runブロックの後で)
#$KCODE = 'u'

# 文字列処理で日本語を考慮した処理メソッドを利用可能にする。
# http://www.ruby-lang.org/ja/man/html/jcode.html
require 'jcode'

# Be sure to restart your server when you modify this file

# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'

# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.0.2' unless defined? RAILS_GEM_VERSION

# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')

Rails::Initializer.run do |config|
...(中略)...
end

# Rails1.2以降のデフォルト設定は'u'。
# Rails1.2以降で任意の文字コードを指定する場合はこの位置で設定するのが良さそう。以下はEUCに設定する例。
#$KCODE = 'e'
#ActionController::Base.default_charset = 'EUC-JP'

require 'gettext/rails'

以下のページが大変参考になりました。感謝です!

  • application_controller.rbは以前と変わらず変更なし。
# app/controllers/application_controller.rb

# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
#  helper :all # include all helpers, all the time

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => 'adc7922e4c5b193da50c06e832eabdf4'

  init_gettext 'test_slip'
end

rakeタスクの修正

  • 翻訳文字列を抽出するためのrakeタスクupdatepoを、拡張子.erb対応にする必要がある。
# lib/tasks/gettext.rake

desc "Update pot/po files."
task :updatepo do
  require 'gettext/utils'
  # Rails2.0から拡張子.erbもRubyとして解析する必要があるので、以下の追記が必要
  GetText::ErbParser.init(:extnames => ['.rhtml', '.erb'])

  GetText.update_pofiles(
    "test_slip",  #テキストドメイン名(init_gettextで使用した名前) 
    Dir.glob("{app,config,components,lib}/**/*.{rb,rhtml,rjs,erb}"),  #ターゲットとなるファイル(文字列内は余分なスペース無しで指定する)
    "test_slip 1.0.0")  #アプリケーションのバージョン
end

desc "Create mo-files"
task :makemo do
  require 'gettext/utils'
  GetText.create_mofiles(true, "po", "locale")
end

*1:Rails1.2からUTF-8に変更になったようだ。