Resolve "Email templates are not translated to zh_CN"
What does this MR do and why?
This MR is to solve the problem that the mail sent is not localized.
Bug reason: An around_action render_with_default_locale
in ApplicationMailer
used default locale instead of recipient language preference.
def render_with_default_locale(&block)
Gitlab::I18n.with_default_locale(&block)
end
Solution: Define mail_with_i18n
in ApplicationMailer
to set the locale according to the recipient's language preference.Also replace mail
with mail_with_i18n
def mail_with_i18n(headers = {}, &block)
locale = if headers[:to].is_a?(String) && !headers[:to].include?(',')
User.find_by_any_email(headers[:to])&.preferred_language || I18n.locale
else
I18n.locale
end
Gitlab::I18n.with_locale(locale) do
mail(headers, &block)
end
end
There are some reasons do this:
Our intention was to rewrite mail
in ApplicationMailer
:
- Why override
mail
: There are about 50 direct calls to mail (excluding spec) in gitlab. It would be very complex and difficult to maintain to set the locale on its caller without overridingmail
- Why override under
ApplicationMailer
: The callers of themail
method are all from theApplicationMailer
class and its subclasses. Overriding themail
method underApplicationMailer
can solve all problems at once
But it is inappropriate for mail
to be rewritten as the base api. So we choose to define mail_with_i18n
to achieve a similar effect. Even this adds modification: replace mail
with mail_with_i18n
.
MR acceptance checklist
This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.
-
I have evaluated the MR acceptance checklist for this MR.