Search code examples
ruby-on-rails-3internationalizationmethod-callabbreviation

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?


Solution

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