rails-i18n icon indicating copy to clipboard operation
rails-i18n copied to clipboard

I18n::Backend::Base pluralize raise instead of falllbacking

Open gmonein opened this issue 4 years ago • 4 comments

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

gmonein avatar Mar 12 '20 12:03 gmonein

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?

zofrex avatar Nov 26 '20 14:11 zofrex

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.

zofrex avatar Nov 27 '20 08:11 zofrex

Related to https://github.com/ruby-i18n/i18n/issues/493

reinaris avatar Jan 12 '22 14:01 reinaris

And there is already a PR opened on ruby-i18n https://github.com/ruby-i18n/i18n/pull/502

reinaris avatar Jan 12 '22 14:01 reinaris