Add I18n.interpolation_keys
Adds a new method, I18n.interpolation_keys, which returns a list of keys needed to fully resolve a translation.
Some examples:
# Suppose we have the following:
# I18n.t 'example.zero' == 'Zero interpolations'
# I18n.t 'example.one' == 'One interpolation %{foo}'
# I18n.t 'example.two' == 'Two interpolations %{foo} %{bar}'
# I18n.t 'example.three' == ['One %{foo}', 'Two %{bar}', 'Three %{baz}']
# I18n.t 'example.one', locale: :other == 'One interpolation %{baz}'
#
# Then we can expect the following results:
# I18n.interpolation_keys('example.zero') #=> []
# I18n.interpolation_keys('example.one') #=> ['foo']
# I18n.interpolation_keys('example.two') #=> ['foo', 'bar']
# I18n.interpolation_keys('example.three') #=> ['foo', 'bar', 'baz']
# I18n.interpolation_keys('one', scope: 'example', locale: :other) #=> ['baz']
# I18n.interpolation_keys('does-not-exist') #=> []
# I18n.interpolation_keys('example') #=> []
In a recent project, I wanted to be able to figure out "What keys are needed for this translation"?
To my surprise, there wasn't a built-in method for this in I18n; the only option was to hand-roll some regex to look for %{...} patterns in the translation.
So now I've tried to implement it here "properly", making use of I18n.config.interpolation_patterns to be more robust with how interpolations are identified by the library -- e.g. it will also match %<foo>.d by default, and respect custom pattern configurations like {{foo}}.
In a recent project, I wanted to be able to figure out "What keys are needed for this translation"?
I'd be keen to know what this project is :) It sounds a little in the vein of LocaleApp, etc.
I think the feature is lightweight enough and it could be useful for others. Please do add some tests here.
@radar Sorry for the slow progress, I was on holiday 😄
I've gone through some more edge cases, added more documentation and tests. Please take a look when you have time!
I'd be keen to know what this project is :) It sounds a little in the vein of LocaleApp, etc.
I did have applications like that in mind when proposing to push this feature into the main I18n project. However, my specific problem was a bit more granular:
In an application, translations may or may not utilise interpolation keys, in each locale. Sometimes, resolving those keys is an "expensive" operation. So as an optimisation, it makes sense to skip trying to resolve any keys that aren't actually being used.
Thanks!