Last active
December 15, 2015 15:59
-
-
Save mikefarmer/5286140 to your computer and use it in GitHub Desktop.
localization debugging in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Allow some helpful debugging of localization issues. | |
# You can see translations in the UI by adding the following (or like it) to your CSS. | |
# .translation_missing { background-color: red; color: white !important; } | |
# .translation_fallback { background-color: green; color: white !important; } | |
# | |
# You will also need to have the following in your development group in your Gemfile: | |
# gem 'term-ansicolor' | |
# | |
# To turn this off, change this to false. | |
LOG_LOCALIZATION_ERRORS = true unless defined?(LOG_LOCALIZATION_ERRORS) | |
if Rails.env.development? && LOG_LOCALIZATION_ERRORS | |
module I18n::Backend | |
module Fallbacks | |
require 'term/ansicolor' | |
include Term::ANSIColor | |
def translate(locale, key, options = {}) | |
return fallback_message(locale, key, super) if options[:fallback] | |
default = extract_non_symbol_default!(options) if options[:default] | |
options[:fallback] = true | |
I18n.fallbacks[locale].each do |fallback| | |
catch(:exception) do | |
translation = super(fallback, key, options) | |
return translation if fallback == locale | |
result = fallback_message(locale, key, translation) | |
return result unless result.nil? | |
end | |
end | |
options.delete(:fallback) | |
return super(locale, nil, options.merge(:default => default)) if default | |
Rails.logger.debug red("--- I18n Missing Translation: #{locale}::#{key} ---") | |
throw(:exception, I18n::MissingTranslation.new(locale, key, options)) | |
end | |
def extract_non_symbol_default!(options) | |
defaults = [options[:default]].flatten | |
first_non_symbol_default = defaults.detect{|default| !default.is_a?(Symbol)} | |
if first_non_symbol_default | |
options[:default] = defaults[0, defaults.index(first_non_symbol_default)] | |
end | |
return first_non_symbol_default | |
end | |
def fallback_message(locale, key, fallback_text) | |
return nil if fallback_text.nil? | |
Rails.logger.debug yellow("--- I18n Fallback: #{locale}::#{key} ---") | |
%(<span class="translation_fallback" title="translation missing: #{locale}, #{key}">#{fallback_text}</span>).html_safe | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment