How can I send mails in a mailer using the recipient's locale. I have the preferred locale for each user in the database. Notice this is different from the current locale (I18n.locale), as long as the current user doesn't have to be the recipient. So the difficult thing is to use the mailer in a different locale without changing I18n.locale:
def new_follower(user, follower)
@follower = follower
@user = user
mail :to=>@user.email
end
Using I18n.locale = @user.profile.locale before mail :to=>... would solve the mailer issue, but would change the behaviour in the rest of the thread.
This simple plugin was developed for rails 2 but seems to work in rails 3 too.
http://github.com/Bertg/i18n_action_mailer
With it you can do the following:
The subject and mail templates are then translated using the user's locale.
I believe the best way to do this is with the great method
I18n.with_locale
, it allows you to temporarily change theI18n.locale
inside a block, you can use it like this:And it'll change the locale just to send the email, immediately changing back after the block ends.
Source: http://www.rubydoc.info/docs/rails/2.3.8/I18n.with_locale
This answer was a dirty hack that ignored I18n's
with_locale
method, which is in another answer. The original answer (which works but you shouldn't use it) is below.Quick and dirty:
Here's an updated version that also supports the '.key' short-hand notation, so you don't have to spell out each key in its entirety.
http://github.com/larspind/i18n_action_mailer
None of the above is really working since the version 3 to translate both subject and content and be sure that the locale is reseted back to the original one... so I did the following (all mailer inherit from that class:
You just need to set the locale before you call the mail() method:
You can use the i18n_subject method which scope the current path so everything is structured:
in the most resent version of rails at this time it's sufficient to use "I18n.locale = account.locale" in the controller and make multiple views with the following naming strategy welcome.html.erb, welcome.it.html.erb and e.g. welcome.fr.html.erb