Viewページで何度も使われている用語を一つにまとめたい
以下のようなViewファイルはよくあると思います。
<table class="table" border="1">
<thead>
<tr>
<th>タイトル</th>
<th>著者</th>
</tr>
</thead>
<tbody>
<% books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.author %></td>
</tr>
<% end %>
</tbody>
</table>
この「タイトル」と「著者」という言葉、他のViewページでもたくさん使われているとします。
もし「著者」という言葉を「作者」に変えないといけなくなった場合に、全てのファイルを修正するのは大変です。
エディターには一括置換機能があったりするので実際それほど大変ではないかもしれませんが。
モデル名.human_attribute_name(:カラム名)でモデルに関連する用語を一つのファイルから参照させる
ロケールの設定はja(日本語)であることが前提です。
human_attribute_name
はActive Modelのメソッドで、activerecord.models スコープにモデル名と属性名の訳語があればそれを使います。
具体的には、このようなファイルを作り、
ja:
books:
title: 'タイトル'
author: '著者'
Viewファイルはhuman_attribute_name
を使ってこのように変更します。
<table class="table">
<thead>
<tr>
<th><%= Book.human_attribute_name(:title) %></th>
<th><%= Book.human_attribute_name(:author) %></th>
</tr>
</thead>
<tbody>
<% books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.author %></td>
</tr>
<% end %>
</tbody>
</table>
「著者」という用語を使っているページがあるなら、全てBook.human_attribute_name(:author)
を使えばOKです。
もし「著者」→「作者」に変更する場合は、config/locales/model.ja.yml
を1箇所変更するだけで済みます。
config/locales/model.ja.yml
にはモデルとカラムを羅列していきますが、
ja:
books:
title: 'タイトル'
author: '著者'
users:
name: '名前'
age: '年齢'
カラム名ではない用語もまとめたい場合はどうすれば良いでしょうか。
例えばbooksの一覧画面でモデルと特に関係のない「おすすめ度」という用語をまとめたい場合です。
<table class="table" border="1">
<thead>
<tr>
<th><%= Book.human_attribute_name(:title) %></th>
<th><%= Book.human_attribute_name(:author) %></th>
<th>おすすめ度</th>
</tr>
</thead>
<tbody>
<% books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.author %></td>
<td><%= book.おすすめ度を割り出す何らかの処理 %></td>
</tr>
<% end %>
</tbody>
</table>
モデルに関係ない用語をlocales以下で管理したい
localesディレクトリは以下のような構造で作ることが出来ます。
config
└── locales
├── model.ja.yml
└── views
├── books
│ ├── index
│ │ └── ja.yml
│ ├── show
│ │ └── ja.yml
│ users
│ ├── index
│ └── ja.yml
viewごとにja.ymlファイルを作り、その中に用語を記載します。
ja:
books:
index:
bestseller: 'ベストセラー'
以下のようにして、Viewテンプレート内部でbooks.index.bestsellerの値を表示させることが出来ます。
books.indexまでは読み込んだことに出来るので、t '.bestseller'
だけでOKです。
このt
メソッドはtranslateの頭文字から来ています。
bestsellerの前にドットがつくので注意してください。
<table class="table" border="1">
<thead>
<tr>
<th><%= Book.human_attribute_name(:title) %></th>
<th><%= Book.human_attribute_name(:author) %></th>
<th><%= t '.bestseller' %></th>
</tr>
</thead>
<tbody>
<% books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.author %></td>
<td><%= book.おすすめ度を割り出す何らかの処理 %></td>
</tr>
<% end %>
</tbody>
</table>
これでモデルと関係ない用語もlocales以下から参照することが出来ます。