Intercept and handle missing translations in helper

Viewed 1034

I have a helper function that generates useful HTML markup. My functions are usually called with some parameters, including some text translated with I18n my_helper( t(:translation_symbol) ).

I use I18n t translation helper for that, which (if left untouched) outputs some <span class="translation missing">...</span> for texts without translation

I was wondering how to best "intercept" this translation missing so

  • I can render them appropriately in my helpers
  • Normal behavior outside my helpers

In my views I should be able to call both

<%= my_helper(t(:my_text)) %> # My helper needs to handle missing translations
<%= t(:my_text) %> # I want default I18n markup (or a custom one) '<span class="translation missing">fr.my_text</span>

My helper

def my_helper(text=nil)
  # Suppose my_text doesn't have a translation, text will have value 
  # => '<span class="translation-missing">fr.my_text</span>'
  if translation_missing?(text)
    # Code to handle missing translation
    doSomething(remove_translation_missing_markup(text))
    notify_translation_missing
  else
    doSomething(text)
  end
end

def translation_missing?(text)
  # Uses some regex pattern to detect '<span class="translation-missing">'
end
def remove_translation_missing_markup(text)
  # Uses some regex pattern to extract my_text from '<span class="translation-missing">fr.my_text</span>'
end

Is there a better way around this ? I feel bad about using a dirty regex solution.

EDIT : extra requirements

  • No additional markup on views : I don't want to look at my files individually to add raise: true or default: xxx for every translation. If there is a need to change the behavior everywhere I can override the t method.
  • In my helpers, I need a convenient way to manipulate, just the translated text if the translation was found, but for missing translations, I need to easily be able to extract the full path of the translation (fr.namespace.translation_symbol), and the original translation symbol (translation_symbol), so I can add myself translation_missing in my custom markup.

EDIT2 : I am thinking of something like that

  • Override t helper to rescue I18n::MissingTranslationData => e
  • If the exception is raised, create and return a custom object that
    • If rendered in a html.erb, will output the usual <span class="translation..."
    • Has useful fields (translation path, translation_string) that I can reuse in my helpers
3 Answers
Related