Skip to content

Commit

Permalink
Merge pull request #520 from piecehealth/kang
Browse files Browse the repository at this point in the history
Provide "I18n::Backend::Fallbacks#on_fallback" hook to allow users to…
  • Loading branch information
radar authored Jun 4, 2020
2 parents c0850ea + 2e43e41 commit 4e9bd53
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
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

0 comments on commit 4e9bd53

Please sign in to comment.