Skip to content

[4.1.0.beta1] I18n Missing Translation Handler doesn't work #13429

@firedev

Description

@firedev

I have this initializers/i18n.rb to make sure english missing translation go through:

module I18n
  class MissingTranslationHandler < ExceptionHandler
    def call(exception, locale, key, options)
      if exception.is_a?(MissingTranslation) && I18n.locale == :en
        key
      else
        super
      end
    end
  end
end

I18n.exception_handler = I18n::MissingTranslationHandler.new

Works in Rails 4.0.1 but in Rails 4.1.0.beta link_to helpers are wrapping the link text in .translation_missing.

Update

After reading the release notes for Rails 4.0.2 I've tried the suggested Error Handler: https://groups.google.com/forum/#!topic/ruby-security-ann/pLrh6DUw998 but it simply doesn't work:

require 'i18n' 

# Override exception handler to more carefully html-escape missing-key results. 
class HtmlSafeI18nExceptionHandler 
  Missing = I18n.const_defined?(:MissingTranslation) ? I18n::MissingTranslation : I18n::MissingTranslationData 

  def initialize(original_exception_handler) 
    @original_exception_handler = original_exception_handler 
  end 

  def call(exception, locale, key, options) 
    if exception.is_a?(Missing) && options[:rescue_format] == :html 
      keys = exception.keys.map { |k| Rack::Utils.escape_html k } 
      key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize } 
      %(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>) 
    else 
      @original_exception_handler.call(exception, locale, key, options) 
    end 
  end 
end 

I18n.exception_handler = HtmlSafeI18nExceptionHandler.new(I18n.exception_handler) 

Even if I remove the body of the call method, so it always returns key, translations are wrapped in span.translation_missing anyway.

I have tried to redefine t() helper like this:

def t key
  I18n.t(key, raise: true)
end

The I18n::MissingTranslationData error is raised, but it's not being intercepted by the handler.

I propose to have a ignore_missing_translation=[:en] setting that would simply ignore missing translations for specified locales. After all this is the point of overriding the error handler.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions