Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide "I18n::Backend::Fallbacks#on_fallback" hook to allow users to… #520

Merged
merged 1 commit into from
Jun 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/i18n/backend/fallbacks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ def translate(locale, key, options = EMPTY_HASH)
begin
catch(:exception) do
result = super(fallback, key, fallback_options)
return result unless result.nil?
unless result.nil?
on_fallback(locale, fallback, key, options) if locale != fallback
return result
end
end
rescue I18n::InvalidLocale
# we do nothing when the locale is invalid, as this is a fallback anyways.
Expand Down Expand Up @@ -80,6 +83,13 @@ def exists?(locale, key, options = EMPTY_HASH)

false
end

private

# Overwrite on_fallback to add specified logic when the fallback succeeds.
def on_fallback(_original_locale, _fallback_locale, _key, _optoins)
nil
end
end
end
end
33 changes: 33 additions & 0 deletions test/backend/fallbacks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,36 @@ def setup
assert_equal false, I18n.exists?(:bar, :'de-DE-XX', fallback: false)
end
end

class I18nBackendOnFallbackHookTest < I18n::TestCase
class Backend < I18n::Backend::Simple
include I18n::Backend::Fallbacks

attr :fallback_collector

private

def on_fallback(*args)
@fallback_collector ||= []
@fallback_collector << args
end
end

def setup
super
I18n.backend = Backend.new
I18n.fallbacks = I18n::Locale::Fallbacks.new(de: :en)
store_translations(:en, :foo => 'Foo in :en', :bar => 'Bar in :en')
store_translations(:de, :bar => 'Bar in :de')
store_translations(:"de-DE", :baz => 'Baz in :"de-DE"')
end

test "on_fallback should be called when fallback happens" do
assert_equal [:"de-DE", :de, :en], I18n.fallbacks[:"de-DE"]
assert_equal 'Baz in :"de-DE"', I18n.t(:baz, locale: :'de-DE')
assert_equal 'Bar in :de', I18n.t(:bar, locale: :'de-DE')
assert_equal 'Foo in :en', I18n.t(:foo, locale: :'de-DE')
assert_equal [:'de-DE', :de, :bar, {}], I18n.backend.fallback_collector[0]
assert_equal [:'de-DE', :en, :foo, {}], I18n.backend.fallback_collector[1]
end
end