Tigraine

Daniel Hoelbling-Inzko talks about programming

Invoking rails i18n.translate with pluralization

Posted by Daniel Hölbling on November 14, 2011

One very nice thing about the internationalization library in Rails is it's support for pluralization by default. Instead of having to figure out how to display a plural or a singular when selecting what message translation you display you can just call translate and it will figure out if the plural or the singular form should be used.

Defining the two forms is done inside your config/locale/.yml like this:

found:
  one: "Found one result"
  other: "Found %{count} results"

This works out of the box for things like validation errors or ActiveRecord models. But it refused to work on me for my own little custom array I was outputting.

Turns out I was just not calling it correctly. I18n.translate simply takes a hash of options - expecting one of these options to be count so it can perform the pluralization check (by default this is entry[count == 1 ? 0 : 1]).

So in order to use this with a custom array you need to write something like this:

I18n.translate :found, :count => myarray.length

Since this allows you to pass any value you want through the arguments hash you can easily construct translations like this:

found:
  one: We could not find anything matching your query %{query}
  other: We found %{count} items

I18n.translate :found, :count => myarray.length, :query => "your query"

Filed under programmierung, rails, ruby
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more