Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse translation with rails-i18n

I've been happily using the built-in rails i18n support for translating strings to different languages, which works great. Recently though I've had a need for something that goes a bit beyond the default behaviour of this gem.

I'll call this "inverse translation" for lack of a better word. Basically the idea is that I have some string in some language, and I want to be able to call a method with another locale, and get back the string translated to that locale if a mapping exists in the locale strings.

For example, assume I have in 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") while in the English locale, with the string and the locale as arguments, I get back the Japanese translation:

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

Also, and this is more tricky, I want to be able to inverse match interpolated strings. So say I have:

config/locales/en.yml

en:
  minutes: "%d minutes"

config/locales/ja.yml

ja:
  minutes: "%d分"

Then I should be able to translate from English to Japanese like so:

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

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

Obviously there are potential problems here, if: 1) there is no match, or 2) there are multiple matches. Those could be handled by raising an exception, for example, or by returning nil in the former case and an array of translations in the latter. In any case those are minor points.

My basic question is: does anything like this exist? And if not, does anyone have any suggestions on how to go about developing it (say as a gem)?

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

Any advice or suggestions would be much appreciated! For reference see also this discussion in 2010 on the topic of inverse translation with i18n-rails.

like image 345
Chris Salzberg Avatar asked Sep 27 '12 09:09

Chris Salzberg


1 Answers

We use gettext, which is a standard unix i18n solution. For Rails, you can use gettext_i18n_rails. One caveat is that FastGettext, which gettext_i18n_rails is backed by, doesn't seem to have complete gettext support, and some advanced features such as pluralization didn't work as expected.

like image 86
Paul McMahon Avatar answered Oct 22 '22 09:10

Paul McMahon