I’m sure I’m not the first one to find this, but here’s a working example for a i18n version of Integer#ordinalize.
Setup
First, you need to define <locale>.rb
files in you lib/locales
folder for each language. Here are examples for English, German, and French:
# lib/locales/en.rb { :en => { :ordinal => proc { |number| number.ordinalize } } }
This is using the built-in ordinalize
extension, which does the English job.
# lib/locales/de.rb { :de => { :ordinal => proc { |number| "#{number}." } } }
German ordinalization is really easy.
# lib/locales/fr.rb { :fr => { :ordinal => proc { |number| "#{number}#{number == 1 ? 'er/re' : 'e'}" } } }
You’ll have to find out how to apply the correct genus all by yourself if you don’t like the self-service-slash :P
More languages can be added, but it gets really complicated for Spanish or Finnish.
Usage
After you restart your server (also in development mode!), I18n.t('ordinal') will return a Proc
object. You can use it in your view like this:
<%= I18n.t('ordinal')[count] + ' ' + I18n.t("article") %>
Notice the use of []
for the object returned by the I18n.t
call: It’s calling the Proc
, passing the number
argument, which is then ordinalized according to the current locale. You could also use .call(count)
, or even .(count)
in Ruby 1.9, but I prefer the brackets.