1 # encoding: utf-8
2
3 # I18n locale fallbacks are useful when you want your application to use
4 # translations from other locales when translations for the current locale are
5 # missing. E.g. you might want to use :en translations when translations in
6 # your applications main locale :de are missing.
7 #
8 # To enable locale specific pluralizations you can simply include the
9 # Pluralization module to the Simple backend - or whatever other backend you
10 # are using.
11 #
12 # I18n::Backend::Simple.send(:include, I18n::Backend::Pluralization)
13 #
14 # You also need to make sure to provide pluralization algorithms to the
15 # backend, i.e. include them to your I18n.load_path accordingly.
16 module I18n
17 module Backend
18 module Pluralization
19 # Overwrites the Base backend translate method so that it will check the
20 # translation meta data space (:i18n) for a locale specific pluralization
21 # rule and use it to pluralize the given entry. I.e. the library expects
22 # pluralization rules to be stored at I18n.t(:'i18n.plural.rule')
23 #
24 # Pluralization rules are expected to respond to #call(entry, count) and
25 # return a pluralization key. Valid keys depend on the translation data
26 # hash (entry) but it is generally recommended to follow CLDR's style,
27 # i.e., return one of the keys :zero, :one, :few, :many, :other.
28 #
29 # The :zero key is always picked directly when count equals 0 AND the
30 # translation data has the key :zero. This way translators are free to
31 # either pick a special :zero translation even for languages where the
32 # pluralizer does not return a :zero key.
33 def pluralize(locale, entry, count)
34 return entry unless entry.is_a?(Hash) and count
35
36 pluralizer = pluralizer(locale)
37 if pluralizer.respond_to?(:call)
38 key = count == 0 && entry.has_key?(:zero) ? :zero : pluralizer.call(count)
39 raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
40 entry[key]
41 else
42 super
43 end
44 end
45
46 protected
47
48 def pluralizers
49 @pluralizers ||= {}
50 end
51
52 def pluralizer(locale)
53 pluralizers[locale] ||= I18n.t(:'i18n.plural.rule', :locale => locale, :resolve => false)
54 end
55 end
56 end
57 end