How to enable Rails I18n translation errors in views?

怎甘沉沦 提交于 2019-12-12 08:53:25

问题


I created new Rails 3 project. I try to use translations in my views like this:

= t('.translate_test')

In my browser i looks "translate_test" instead "my test translation" witch i set in en.yml.

My main question - why i can't see error like "Missing translation: en ..." ?


回答1:


In Rails 3 they don't show you this text anymore. If you inspect the element in the html source you will see the translation missing message.

You can turn fallbacks off, try to put in your environment or an initializer the following:

config.i18n.fallbacks = false



回答2:


I've created this initializer to raise an exception - args are passed so you will know which i18n key is missing!

# only for development and test
if Rails.env.development? || Rails.env.test?

  # raises exception when there is a wrong/no i18n key
  module I18n
    class JustRaiseExceptionHandler < ExceptionHandler
      def call(exception, locale, key, options)
        if exception.is_a?(MissingTranslationData)
          raise exception.to_exception
        else
          super
        end
      end
    end
  end

  I18n.exception_handler = I18n::JustRaiseExceptionHandler.new

end

Source




回答3:


I use the simplest and view specific solution to display the errors in View when the translation is missing by adding this style in your application.css.scss or any global stylesheet:

.translation_missing{
  font-size: 30px;
  color: red;
  font-family: Times;

  &:before{
   content: "Translation Missing :: ";
   font-size: 30px;
   font-family: Times;
   color: red;
 }
}



回答4:


Add a monkeypatch in your application.rb in order that an exception will be thrown when a translation is missing:

module ActionView::Helpers::TranslationHelper
  def t_with_raise(*args)
    value = t_without_raise(*args)

    if value.to_s.match(/title="translation missing: (.+)"/)
      raise "Translation missing: #{$1}"
    else
      value
    end
  end
  alias_method :translate_with_raise, :t_with_raise

  alias_method_chain :t, :raise
  alias_method_chain :translate, :raise
end


来源:https://stackoverflow.com/questions/8551029/how-to-enable-rails-i18n-translation-errors-in-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!