Reverse translation with rails-i18n

I gladly used the built-in rails i18n support for translating strings into different languages, which works great. Recently, although I had a need for something that is slightly different from the default behavior of this gem.

I will call this “ reverse translation due to the lack of a better word. In fact, the idea is that I have a string in some language, and I want to be able to call a method with a different language and return a string translated to this locale if there is a match in the language strings.

For example, suppose I have config/locales/en.yml

 en: hello: Hello World! 

and in config/locales/ja.yml :

 ja: hello: Konnichi wa! 

then when I call this method l2l_translate ("locale to locale translate"), and in the English locale, with string and language as arguments, I return the Japanese translation:

 I18n.locale = :en l2l_translate("Hello World!", :ja) #=> "Konnichi wa!" 

In addition, and it is more complicated, I want to be able to invert the correspondence of interpolated strings. So say that I have:

<strong> Config / locale / en.yml

 en: minutes: "%d minutes" 

<strong> Config / locales / ja.yml

 ja: minutes: "%d分" 

Then I can translate from English to Japanese like this:

 l2l_translate("5 minutes", :ja) #=> "5分" 

So, basically the string should be matched with the regular expression with the English translation string, and "5" pulled out and sent as the argument "% d" to the Japanese translation.

Obviously, there are potential problems if: 1) there is no match, or 2) there are several matches. They could be treated, for example, by creating an exception or by returning nil in the former case and an array of translations in the latter. In any case, these are small points.

My main question is: does something like this exist? And if not, does anyone have any suggestions on how to develop it (say, like a gem)?

The application I'm thinking of now is a wrapper API for a service in Japanese. I want to be able to specify patterns in Japanese that can be matched and translated into other languages. The default support for i18n will not do this, and I do not know of any other gems that will be.

Any advice or suggestions would be greatly appreciated! For reference, also see this 2010 discussion on the topic of reverse translation from i18n-rails.

+4
source share
1 answer

We use gettext , which is a standard unix i18n solution. For Rails, you can use gettext_i18n_rails . One caveat is that FastGettext, with which gettext_i18n_rails is supported, does not seem to have full gettext support, and some additional features, such as pluralization, do not work as expected.

+2
source

Source: https://habr.com/ru/post/1436563/


All Articles