Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails I18n: shorten the translate calls (at least in the views)

What is the DRY way to translate certain fields?

In my RESTful views, I have some repeating snippets, like this in a show-view:

...
<dt><%= t("activerecord.attributes.user.firstname") %></dt>
<dd><%= @user.firstname %></dd>
...

Now, instead of writing t("activerecord.attributes.user.attr_name") over and over again, I'd like to write only t(:attr_name) (similar to f.label :firstname in the form-views).

Basically, this should not be a problem (at least for the RESTful views), since the I18n module could query the controller method to extrapolate the model name and then just guess the correct translation string.

My question: Did anyone have practical experience with this approach? Could there even be a RubyGem for it? Or: are there pitfalls, I didn't think of?

like image 710
DMKE Avatar asked Jul 24 '11 20:07

DMKE


2 Answers

I seems, ActiveModel::Translation#human_attribute_name does the trick (e.g. <%= User.human_attribute_name :firstname %>).

like image 159
DMKE Avatar answered Dec 07 '22 16:12

DMKE


The recommended way to do this is to put this into a partial (e.g. app/views/user/_form.html.erb or even app/views/user/_user.html.erb), and then precede the name with a leading dot, thus:

<dt><%= t(".firstname") %></dt>
<dd><%= user.firstname %></dd>

More information: examples (from Agile Web Development with Rails); Rails documentation

like image 25
Sam Ruby Avatar answered Dec 07 '22 16:12

Sam Ruby