Forum: Rails I18n Delocalization

05c3f39db309047f28628a223a757bec?d=identicon&s=25 Hans Marmolin (marmolin)
on 2010-12-15 20:41
(Received via mailing list)
Hi
I and others have earlier discussed the need for delocalization
(inverse translation) methods. Sven proposed a solution that did not
work for me but for some others. As Sven said that solution was a kind
of fix.

I have now implemented a solutions and would like to have some
comments. The main problem is to find a solution as independen of the
way keys are used as possible.

In my soution one  call with the word to be delocalized and the method
then makes an extended search through all translations to find the
key,that then is used for delocalization.
Any comments one that solution.?
Is it to ineffective ?
I add the code below so you can propose improvements
I use it as an extension to the string class, but it can of course be
used in other ways.

   # Delocalizes a string.
   # Delocalization means to transform a localized string to the
original used in the code, preferreble an en-string
   # Searchs for the string in all translations and uses the key of
the found translation to delocalize.
   # If the last word in the translation key is a dasherized version
of the string, then it is used for delocalization
   # Call with to_local= blank (or not used)
   # In all other cases call with to_locale = the language to be
delocalized to. The translation of that language will be used for
delocalization

   def to_delocalize(to_locale='')

     def collect_keys(scope, translations)
       full_keys = []
       translations.to_a.each do |key, translations|
         new_scope = scope.dup << key
         if translations.is_a?(Hash)
           full_keys += collect_keys(new_scope, translations)
         else
           full_keys << new_scope.join('.')
         end
       end
       return full_keys
     end
     I18n.backend.send(:init_translations)
     all_keys = I18n.backend.send(:translations).collect do |
check_locale, translations|
       collect_keys([], translations).sort
     end.flatten.uniq
    delocalized_string=''
    key=''
     all_keys.each do |key|
         result = I18n.translate(key)
         if result==self
              delocalized_string=key.split('.').last
              break
         end
      end
     if !to_locale.blank?
        I18n.locale = to_locale.to_sym
        delocalized_string = I18n.translate(key)
      end
      return delocalized_string
   end
This topic is locked and can not be replied to.