5

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?

DMKE
  • 4,553
  • 1
  • 31
  • 50

2 Answers2

6

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

DMKE
  • 4,553
  • 1
  • 31
  • 50
2

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

Sam Ruby
  • 4,270
  • 22
  • 21
  • 3
    The usage of partials seems to be quiet nice, but I think it will only be DRY, if the same content will be displayed repetively. The documentation also says, calling `t('.foo')` from the people/index.html.erb template is actually calling `t('people.index.foo')`. I don't want to maintain the mess in my locale files... – DMKE Jul 24 '11 at 22:41