From c5c6e753f31e2c107925cee5fce37639d68a6a9d Mon Sep 17 00:00:00 2001 From: Nerian Date: Thu, 9 Mar 2023 12:32:32 +0100 Subject: [PATCH] When there is a translation missing error, show all the potential keys that would have matched the missing one. --- lib/i18n/exceptions.rb | 14 ++++++++++++-- test/i18n/exceptions_test.rb | 6 ++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/i18n/exceptions.rb b/lib/i18n/exceptions.rb index 74db4d34..c9908973 100644 --- a/lib/i18n/exceptions.rb +++ b/lib/i18n/exceptions.rb @@ -47,7 +47,7 @@ def initialize(filename, exception_message) class MissingTranslation < ArgumentError module Base - PERMITTED_KEYS = [:scope].freeze + PERMITTED_KEYS = [:scope, :default].freeze attr_reader :locale, :key, :options @@ -63,8 +63,18 @@ def keys end def message - "translation missing: #{keys.join('.')}" + if options[:default].is_a?(Array) + other_options = ([key, *options[:default]]).map { |k| normalized_option(k).prepend('- ') }.join("\n") + "Translation missing. Options considered were:\n#{other_options}" + else + "Translation missing: #{keys.join('.')}" + end + end + + def normalized_option(key) + I18n.normalize_keys(locale, key, options[:scope]).join('.') end + alias :to_s :message def to_exception diff --git a/test/i18n/exceptions_test.rb b/test/i18n/exceptions_test.rb index 771308d0..3920bf91 100644 --- a/test/i18n/exceptions_test.rb +++ b/test/i18n/exceptions_test.rb @@ -32,6 +32,12 @@ def test_invalid_locale_stores_locale end end + test "MissingTranslationData message contains all potential options" do + force_missing_translation_data(default: [:option_a, :option_b]) do |exception| + assert_equal "translation missing. Options considered were:\n- de.bar.option_a, \n- de.bar.option_a", exception.message + end + end + test "InvalidPluralizationData stores entry, count and key" do force_invalid_pluralization_data do |exception| assert_equal({:other => "bar"}, exception.entry)