Skip to content

Commit

Permalink
Fix error when including Fallbacks on non-Simple backend
Browse files Browse the repository at this point in the history
Commit 12aa0f0 introduced a bug, where
if `Fallbacks` module is included in a class that doesnt define
`translations` the code would fail. This is a pretty common
scenario, for instance when the backend is a `Chain`. Also this was
pretty common case to fail in rails, as its include Fallbacks in the
I18n.backend, like this:
```
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
```

This stops using the `translations` method in the fallbacks, and instead
ignores `I18n::InvalidLocale` errors.

[fixes #238]
[fixes #258]
[fixes #259]
  • Loading branch information
arthurnn committed May 29, 2014
1 parent 667bcfe commit f4d1d8f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
11 changes: 7 additions & 4 deletions lib/i18n/backend/fallbacks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,13 @@ def translate(locale, key, options = {})

options[:fallback] = true
I18n.fallbacks[locale].each do |fallback|
next unless translations.keys.include?(fallback)
catch(:exception) do
result = super(fallback, key, options)
return result unless result.nil?
begin
catch(:exception) do
result = super(fallback, key, options)
return result unless result.nil?
end
rescue I18n::InvalidLocale
# we do nothing when the locale is invalid, as this is a fallback anyways.
end
end
options.delete(:fallback)
Expand Down
11 changes: 11 additions & 0 deletions test/backend/fallbacks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,21 @@ class Backend < I18n::Backend::Simple
def setup
backend = Backend.new
backend.store_translations(:de, :foo => 'FOO')
backend.store_translations(:'pt-BR', :foo => 'Baz in :pt-BR')
I18n.backend = I18n::Backend::Chain.new(I18n::Backend::Simple.new, backend)
I18n.backend.class.send(:include, I18n::Backend::Fallbacks)
end

test "falls back from de-DE to de when there is no translation for de-DE available" do
assert_equal 'FOO', I18n.t(:foo, :locale => :'de-DE')
end

test "should not raise error when enforce_available_locales is true, :'pt' is missing and default is a Symbol" do
I18n.enforce_available_locales = true
begin
assert_equal 'Foo', I18n.t(:'model.attrs.foo', :locale => :'pt-BR', :default => [:'attrs.foo', "Foo"])
ensure
I18n.enforce_available_locales = false
end
end
end

0 comments on commit f4d1d8f

Please sign in to comment.