Created
August 31, 2021 03:56
-
-
Save westonganger/ebfe3a9709aa63481bfdff2a9b8d4b43 to your computer and use it in GitHub Desktop.
Rails I18n Exception Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### CUSTOM I18N EXCEPTION HANDLER | |
### 1. This exception handler enforces that an exception is raised whenever a translation is not found rather than showing "translation missing" to user | |
### 2. YOU CAN USE I18n.t(key, fallback: true) and it will now handle missing translations as follows: | |
### | |
### If a specific key is used ie. 'fisheries.locations.asd' and the translation is not found then it will look for: | |
### - 'common.asd' | |
### | |
module I18n | |
class CustomExceptionHandler < ExceptionHandler | |
def call(exception, locale, key, options) | |
if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule' | |
if options[:fallback] | |
generic_key = "common.#{key.to_s.split(".").last}" | |
alt_key = nil | |
# if key.to_s.include?("_form.") | |
# alt_key = key.to_s.split(".")[-2..-1].join(".") | |
# end | |
if I18n.exists?(generic_key) | |
return I18n.t(generic_key, fallback: false) | |
elsif alt_key && I18n.exists?(alt_key) | |
return I18n.t(alt_key, fallback: false) | |
else | |
raise exception.to_exception | |
end | |
else | |
raise exception.to_exception | |
end | |
else | |
super | |
end | |
end | |
end | |
end | |
I18n.exception_handler = I18n::CustomExceptionHandler.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment