ruby-i18n/i18n

Add an I18n.exists? check that does not fall back

Closed this issue ยท 7 comments

What I tried to do

Prerequisites: fallbacks are enabled and there is a fallback value for the key.

Check whether a locale entry exists for a key.

What I expected to happen

I18n.exists? used to return false, because the key was not present in the locale and fallbacks were not considered.

What actually happened

I18n.exists? now returns true, because fallbacks are now considered.

Versions of i18n, rails, and anything else you think is necessary

Please note that this is not a bug report, but rather a feature request.

The behavior change was introduced through #326. I believe that the change is correct and that the previous implementation was erroneous: I18n.exists? should fall back by default when fallbacks are enabled.

However, now there is no way to check for key presence without falling back automatically and thus getting false results. I recommend either:

  • Introducing an optional parameter or in the options hash: def exists?(..., skip_fallbacks = false)
  • Introducing another method: def exists_in_locale?

My workaround for the moment is to raise and catch errors, but it would be nice for exists? to accept the fallback parameter similar to translate

begin
  I18n.t(key, locale: locale, fallback: false, raise: true)
rescue I18n::MissingTranslationData
  false
else
  true
end

Interesting workaround. I am thinking of monkey-patching it into I18n as my_exists? until something similar is re-introduced into the gem.

@svenfuchs any thoughts on extending exists? with optional parameters and thus unblocking us from v0.7.0?

translate and exists? are meant to behave the same, it would make sense to me if exists? would also consider options, e.g. fallback: false.

Currently 'exists?' calls 'lookup', which in return takes options (translate is passing the fallback option to lookup).

So if I am not mistaken it should be as easy as allowing to pass options through exists? to lookup.

๐Ÿ‘‹ Hi everyone, is this something we still want to add to the library? If so I've opened a PR for it, let me know what you guys think :)

#482

cc: @radar

From a dev perspective, this is exactly what I need. :)

#482 was merged into master. Closing...

Aryk commented

How can one get the language for the key after the fallbacks are applied? For example, if I want to see what language it falls back to, how could I do that?