0

I have my model names declared in config/locales/models.en.yml:

en:
  activerecord:
    models:
        news_item:
            zero: No News Items
            one: News Item
            other: News Items

I know I can get the correctly pluralized model name using:

NewsItem.model_name.human(count: n)

So I could do:

"#{n} {NewsItem.model_name.human(count: n)}

Which is fine for 1 and many items, but with no items will render:

0 No News Items

Obviously I can add some logic to skip rendering the numeric part if there are no items, but I'm wondering if Rails has this built in?

There is a basic translation method that does what I'm after, but it doesn't pick up on model name translations:

I18n.translate :news_item, count: 2

Gives the error:

"translation missing: en.news_item"

Undistraction
  • 42,754
  • 56
  • 195
  • 331
  • Is this helpful ? http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-pluralize – Arup Rakshit Aug 23 '15 at 08:40
  • @ArupRakshit Nope. Because that takes no notice of the model name(s) in the locale file. – Undistraction Aug 23 '15 at 08:42
  • instead of `0 No News Items` you want `No News Items` ? – Arup Rakshit Aug 23 '15 at 08:44
  • I said you to use something like `NewsItem.model_name.human(count: n).pluralize` – Arup Rakshit Aug 23 '15 at 08:46
  • @ArupRakshit That makes no sense. You are asking the model to give you the correct (pluralized or not) translated name for the given count and then pluralizing it. I want the equivalent of `I18n.translate :news_items, count: n` but using the model's `human_name` which is drawn from the locale file. – Undistraction Aug 23 '15 at 08:46
  • As you got the error, `I18n.translate :news_items, count: 2` will work if you rename the model name in the translation file to `news_items`. – Arup Rakshit Aug 23 '15 at 08:57
  • The extra `s` was a typo, but the error is the same either way. – Undistraction Aug 23 '15 at 09:20

1 Answers1

0

Seems like the answer is no, so I've created a helper method that does this:

  def humanize_with_prefixed_count(clazz, count)
    [count, clazz.model_name.human(count: count)].delete_if{ |x| x == 0}.join(' ')
  end

Use:

humanize_with_prefixed_count(NewsItem, 0) # No NewsItems
humanize_with_prefixed_count(NewsItem, 1) # 1 NewsItem
humanize_with_prefixed_count(NewsItem, 2) # 2 NewsItems

clazz.model_name.human # News Item
Undistraction
  • 42,754
  • 56
  • 195
  • 331