第31回Rails勉強会@東京のセッション「Rails 2.2の I18nについてくわしく」の資料

●I18nモジュールとは

●ソース

github からこんな感じで検索してみる。
http://github.com/rails/rails/search?q=i18n&choice=grep

●重要そうなコミット

●基本機能

I18nというライブラリのクラスメソッドがいくつか提供されている。

>> [I18n.local_methods - Object.methods]
=> [["append_features", "backend", "backend=", "default_exception_handler", "default_locale", "default_locale=", "exception_handler=", "l", "locale", "locale=", "localize", "normalize_translation_keys", "populate", "store_translations", "t", "translate"]]

デフォルトの localeは en-USになっている。

>> I18n.locale
=> "en-US"

ja-JPに変更してみる。

>> I18n.default_locale = 'ja-JP'

詳しくはソースで。

●ソースの読みどころ

  • I18n gemの本体
    activesupport/lib/active_support/vendor/i18n-0.0.1/ 以下
  • 基本的な操作とか
    activesupport/lib/active_support/vendor/i18n-0.0.1/lib/i18n.rb
  • vendor/rails/activerecord/lib/active_record/validations.rb

●機能その1. translate

翻訳メソッド。

>> I18n.t 'hoge'
=> "translation missing: ja-JP, hoge"
>> I18n.t 'hoge', :default => 'ほげ'
=> "ほげ"
>> I18n.store_translations :'ja-JP', :hoge => 'ホゲ'
=> {:hoge=>"ホゲ"}
>> I18n.t 'hoge'
=> "ホゲ"
>> I18n.t 'hoge', :default => 'ほげ'
=> "ホゲ"

 

●機能その2. localize

日付や時刻、お金のフォーマット

% lv vendor/rails/activesupport/lib/active_support/locale/en-US.rb

 

I18n.backend.store_translations :'en-US', {
  :support => {
    :array => {
      :sentence_connector => 'and'
    }
  },
  :date => {
    :formats => {
      :default => "%Y-%m-%d",
      :short => "%b %d",
      :long => "%B %d, %Y",
    },
    :day_names => Date::DAYNAMES,
    :abbr_day_names => Date::ABBR_DAYNAMES,
    :month_names => Date::MONTHNAMES,
    :abbr_month_names => Date::ABBR_MONTHNAMES,
    :order => [:year, :month, :day]
  },
  :time => {
    :formats => {
      :default => "%a, %d %b %Y %H:%M:%S %z",
      :short => "%d %b %H:%M",
      :long => "%B %d, %Y %H:%M",
    },
    :am => 'am',
    :pm => 'pm'
  }
}

 

●サンプルアプリを作ってみる

  • ja-JP.rbという名前のファイルを $RAILS_ROOT/lib/locale/ に配置する。
    自分で作るのはめんどくさいので gettext-railsからパチっちゃえ。
    たぶんこんな感じで。
% cp vendor/rails/activerecord/lib/active_record/locale/en-US.rb lib/locale/

% cp /opt/local/lib/ruby/gems/1.8/gems/gettext-1.91.0/po/ja/rails.po lib/locale/

% fgrep '%{fn}' rails.po | ruby -e 'puts STDIN.read.gsub("msgid ", "s/").gsub("\nmsgstr ", "/").gsub(/%\{fn\} ?/, "").gsub(/$/, "/")' > trans.sed

% sed -f trans.sed en-US.rb | sed s/en-US/ja-JP/ > ja-JP.rb
  • application_controller に以下の filterを設定
before_filter :set_locale
 
  def set_locale
    locale = params[:locale] || 'ja-JP'
    I18n.locale = locale
    I18n.populate do
      require "lib/locale/#{locale}.rb"
    end
  end
  • つついて遊んでみる

Sorry, comments are closed for this article.