Ruby on Rails 3.2 Mailer, localize the mail subject field

I am currently writing an email program in RoR 3.2 that sends mail that should be localized based on the user's language. I managed to display the correct localized views, but I'm having some difficulties with some fields that require changing the locale (for example, an object). I already read a few posts that contradict the language change before sending the email. Users have many different languages, and this will mean changing my locale every time an email is sent to the user.

I know that it will be possible to change the locale, send an email, change the locale. It doesn’t look like a rail track. Is there a proper way to do this?

Here is a snippet:

class AuthMailer < ActionMailer::Base add_template_helper(ApplicationHelper) default :from => PREDEF_MAIL_ADDRESSES::System[:general] [...] def invite(address, token, locale) @token = token @locale = locale @url = url_for(:controller => "signup_requests", :action => "new", :token => token.key, :locale => locale) mail(:subject => "Invitation", :to => address) do |format| format.html { render ("invite."+locale) } format.text { render ("invite."+locale) } end end [...] end 

My views

 auth_mailer invite.en.html.erb invite.en.text.erb invite.it.html.erb invite.it.text.erb ... 

In short, in this case, I would like to localize the subject: subject using @locale, but without doing: I18n.locale = locale

+7
source share
3 answers

OK to temporarily change the global locale. There is a convenient method I18n.with_locale for this. ActionMailer also automatically translates the theme.

 class AuthMailer def invite(address, token, locale) @token = token @locale = locale @url = url_for(:controller => "signup_requests", :action => "new", :token => token.key, :locale => locale) I18n.with_locale(locale) do mail(:to => address) end end end 

In the locale:

 en: auth_mailer: invite: subject: Invitation 
+30
source

Rails 4 way :

 # config/locales/en.yml en: user_mailer: welcome: subject: 'Hello, %{username}' # app/mailers/user_mailer.rb class UserMailer < ActionMailer::Base def welcome(user) mail(subject: default_i18n_subject(username: user.name)) end end 

default_i18n_subject . Translates the theme using the Rails I18n class in the [mailer_scope, action_name] scope. If he does not find a translation for an item in the specified area, it will by default be characterized as the version of action_name. If the object has interpolations, you can pass them through the interpolation parameter.

+6
source

You should be able to pass in the locale when you call I18n as follows:

 mail(:subject => I18n.t("app.invite.subject", :locale => locale), :to => address) do |format| format.html { render ("invite."+locale) } format.text { render ("invite."+locale) } end 

Remember that the locale variable must be a symbol.

+4
source

All Articles