diff --git a/config/initializers/locale.rb b/config/initializers/locale.rb index 86ae3c07b611ceaf3c571a45c30394717b28f944..8ff5ec7f2c39377ba4203ca4dcc5635fa263a301 100644 --- a/config/initializers/locale.rb +++ b/config/initializers/locale.rb @@ -14,3 +14,5 @@ AVAILABLE_LANGUAGE_CODES.each do |c| I18n.fallbacks[c.to_sym] = [c.to_sym, DEFAULT_LANGUAGE.to_sym, :en] end end +require 'i18n_interpolation_fallbacks' +I18n::Backend::Simple.send(:include, I18n::Backend::InterpolationFallbacks) diff --git a/lib/i18n_interpolation_fallbacks.rb b/lib/i18n_interpolation_fallbacks.rb new file mode 100644 index 0000000000000000000000000000000000000000..45c6dfe59b7e41133c8f8cd0fca06cf75eb7b4e5 --- /dev/null +++ b/lib/i18n_interpolation_fallbacks.rb @@ -0,0 +1,24 @@ +module I18n + module Backend + module InterpolationFallbacks + + def translate(locale, key, options = {}) + return super if options[:fallback] + default = extract_string_or_lambda_default!(options) if options[:default] + + options[:fallback] = true + I18n.fallbacks[locale].each do |fallback| + begin + result = super(fallback, key, options) + return result unless result.nil? + rescue I18n::MissingInterpolationArgument + end + end + options.delete(:fallback) + + return super(locale, nil, options.merge(:default => default)) if default + raise(I18n::MissingInterpolationError.new(locale, key, options)) + end + end + end +end diff --git a/spec/misc_spec.rb b/spec/misc_spec.rb index e01f93f17d5ead744ca51430358b39beb1ffbc16..d11402caaec1098a2ac1cf7e4292b7c96431515c 100644 --- a/spec/misc_spec.rb +++ b/spec/misc_spec.rb @@ -62,4 +62,19 @@ describe 'making sure the spec runner works' do end end + describe I18n do + include ActionView::Helpers::TranslationHelper + it 'MissingInterpolationError in a non-english locale is not fatal' do + I18n.locale = 'it' + I18n.backend.should_receive(:lookup).ordered. + with(:it, 'bob', nil, :hey => "what", :fallback => true). + and_return("%{not_present} failure") + I18n.backend.should_receive(:lookup).ordered. + with(:en, 'bob', nil, :hey => "what", :fallback => true). + and_return("English translation") + translation = translate('bob', :hey => "what") + translation.should == "English translation" + end + end + end