Search code examples
ruby-on-railsrubyrails-i18ni18n-gem

Ruby i18n.translate having :raise => true as default behaviour


When i call:

t 'to_translate'

method from my template, I would like it to raise an error without actually passing second parameter like this:

t 'to_translate', :raise => true

It would save me a lot of typing in every translation I do. Or is there a workaround for this?

Thanks for answers.


Solution

  • You can find the answer on the I18n documentation paragraph 6.2

    "[..] the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with #call method:

    module I18n
      class JustRaiseExceptionHandler < ExceptionHandler
        def call(exception, locale, key, options)
          if exception.is_a?(MissingTranslation)
            raise exception.to_exception
          else
            super
          end
        end
      end
    end
    
    I18n.exception_handler = I18n::JustRaiseExceptionHandler.new
    

    This would re-raise only the MissingTranslationData exception, passing all other input to the default exception handler."

    Learn more on http://guides.rubyonrails.org/i18n.html#using-different-exception-handlers