勉強会でi18n使ったので復習

3/28のRBCイケテルRails勉強会で、i18nを使ったが、説明不足を感じ、復習。
以下の、テンプレートファイルを適用すると、scaffoldで生成したproductモデルのViewが諸々日本語化される。

# i18n_generators プラグインインストール
plugin 'i18n_generators', :git => 'git://github.com/amatsuda/i18n_generators.git'

# i18n_scaffold生成 -> product
generate(:i18n_scaffold, "product title:string description:text price:decimal")

# 日本語をデフォルトとする(i18n:internationalization)
generate :i18n, "ja"

app/views/products/index.html.erb の一部を例に挙げると、

<td><%= link_to translate(:show, :default => 'Show', :scope => [:railties, :scaffold]), product %></td>
<td><%= link_to translate(:edit, :default => 'Edit', :scope => [:railties, :scaffold]), edit_product_path(product) %></td>

translate(...、ってあるのでここで翻訳しているのね、というのが分かる。
で、つぎに config/locales/translation_ja.yml を覗くと、

となっている。:scope => [:railties, :scaffold]でスコープを指定して、そこの:showや:editを取ってきているということが分かる。
では、script/console で確認してみよう。

I18n.translate は I18n.t でもいけるみたい。勉強会のときはこのように説明した方がよかっただろうと思う。
(additional : viewのローカライズについて)
日本語をデフォルトとすると、config/enviroments.rb に

config.i18n.default_locale = 'ja'

の記述ができている。で、そうなると、たとえば、app/views/products/index.ja.html.erb を用意すると、
http://localhost:3000/products にアクセスした際にデフォルトでレンダリングされる
app/views/products/index.html.erb ではなく、
app/views/products/index.ja.html.erb がレンダリングされる。