Skip to content

Commit

Permalink
Provide "I18n::Backend::Fallbacks#on_fallback" hook to allow users to…
Browse files Browse the repository at this point in the history
… add specified logic when the fallback succeeds.
  • Loading branch information
piecehealth committed Mar 12, 2020
1 parent eac7a9e commit 8ada2c4
Show file tree
Hide file tree
Showing 2 changed files with 42 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)
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
31 changes: 31 additions & 0 deletions test/backend/fallbacks_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,34 @@ 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')
end

test "on_fallback should be called when fallback happens" do
assert_equal [:"de-DE", :de, :en], I18n.fallbacks[:"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 8ada2c4

Please sign in to comment.