Rails 2.2 の i18n を使ってみた

Rails 2.2.2 で i18n を使ってみました。

前評判はイマイチだったので、どんな感じなのかなと思っていたけど、個人的には GetText より好きです。

手順としてはプロジェクトを作成して、scaffold を実行した後、以下を実行します。

gem so -a http://gems.github.com
gem install amatsuda-i18n_generators
ruby script/generate i18n ja

ただ、これだけでは、一部問題がありエラーメッセージが日本語化されないようです。(amatsuda-i18n_generators v0.4)

ということで、生成後の yml を3行消します。

config/locales/ja.yml

ja:
(省略)
  activerecord:
    errors:
      template:
        header:
          one:   "{{model}}にエラーが発生しました。"
          other: "{{model}}に{{count}}つのエラーが発生しました。"
-  activerecord:
-    errors:
-      template:
        body: "次の項目を確認してください。"

      messages:
(省略)

これで日本語化できました。簡単ですね。

label の日本語化

これだけでは label は日本語化されないみたいなので、label の日本語化を作ってみた。
config/initializers/libs.rb

require 'active_record_helper'

lib/active_record_helper.rb

module ActionView
  module Helpers
    module FormHelper
      def label_with_ja(object_name, method, text = nil, options = {})
        if text.nil?
          text = I18n.t(method, :default => method, :scope => [:activerecord, :attributes, object_name])
        end
        label_without_ja(object_name, method, text, options)
      end
      alias_method_chain :label, :ja  #:nodoc:
    end
  end
end

これで label も translation_ja.yml で指定した attributes 名が表示されます。

参考

2 Comments

  1. babydaemons より:

    このエントリでとっても助かりました。ありがとうございました。

  2. solis より:

    labelの日本語化が役立ちました。
    ありがとうございました。

Leave a Reply