How to translate email messages body using the I18n gem? How to translate email messages body using the I18n gem? ruby ruby

How to translate email messages body using the I18n gem?


Solution

In your railsproject make a mailer (read http://guides.rubyonrails.org/action_mailer_basics.html how to make one). For example UserMailer.

rails g mailer UserMailer

Define a method for example mail_user.

def mail_user(user)    @user = user    mail(:to => "test example <testuser@testuser.com>", :subject => "hello")end

Now define views. For example: mail_user.de.html.erb and mail_user.en.html.erb. Put your translations in there. If you want to translate variables seperatly use:

<%= I18n.t("foo.bar") %>

When you do this, ensure you have a en.yml and de.yml translation! Define a translation like the following example:

foo:    bar: hello

You should be ready to go.

How this works

ActionMailer works the following way. You can create mailer models which inherit from ActionMailer::Base. Like ActionController the models have associated views (templates) in the /app/views/ directory.

Now here is the technical part and why this all magicly works. ActionController and ActionMailer default include AbstractController::Rendering directly or indirectly (ActionController::Metal::Rendering). AbstractController::Rendering uses ActionView as default library for its template rendering engine and includes AbstractController::ViewPaths and an instance of I18n proxy to find localized views. To learn more i'd like to refer to the ActionPack source code on github.

To get to the point. ActionView allows you to use localisation in your templates: See Rails guide: Action View Overview , Chapter Localized views.