rails-i18n
rails-i18n copied to clipboard
I18n::Backend::Base pluralize raise instead of falllbacking
Hello,
Wit a yml like this:
en:
toto:
other: en_totos
one: en_toto
fr:
toto:
other: fr_totos
And all fallback things, I18n raise me an error
irb(main):002:0> I18n.locale = :fr ; I18n.t('toto', count: 1)
Traceback (most recent call last):
2: from (irb):2
1: from config/initializers/i18n.rb:10:in `pluralize'
I18n::InvalidPluralizationData (translation data {:other=>"en_totos"} can not be used with :count => 1. key 'one' is missing.)
but i want this
irb(main):001:0> I18n.locale = :fr ; I18n.t('toto', count: 1)
=> "en_toto"
I fixed it by adding this code into config/initializer/i18n.rb
module I18n
module Backend
module Base
def pluralize(locale, entry, count)
return entry unless entry.is_a?(Hash) && count && entry.values.none? { |v| v.is_a?(Hash) }
key = pluralization_key(entry, count)
# raise InvalidPluralizationData.new(entry, count, key) unless entry.has_key?(key) # old code
throw(:exception, I18n::MissingTranslation.new(locale, "#{entry}.#{key}", {})) unless entry.has_key?(key)
entry[key]
end
end
end
end
As I18n::Backend::Base.resolve/translate methods are wrapped into an catch(:exception)
for managing falllbacks
This would be helpful for me, too. Is the fix as simple as it looks, or would there be other consequences of changing this to a throw :exception
?
To answer my own question: one consequence of this is that even if you throw a InvalidPluralizationData
, it gets turned into a MissingTranslation
by the time it hits the exception handler, which carries less information about what actually happened. I think the fallback code would also need to be adjusted to let this through, and probably the default exception handler as well.
Related to https://github.com/ruby-i18n/i18n/issues/493
And there is already a PR opened on ruby-i18n https://github.com/ruby-i18n/i18n/pull/502