user12882
user12882

Reputation: 4792

Trouble on using the i18n gem with the mailer

I am using Ruby on Rails 3.1 and I would like to know how to correctly handle internationalization related to the mailer. That is, ...

... in my app/views/users/mailer/_custom.html.erb file I have:

...
<%= @test_email.to_s %>
...

... in my app/mailers/users/mailer.rb file I have:

class Users::Mailer < ActionMailer::Base
  def custom(user)
    ...
    @test_email = t('test_email')
    # I also tried to use '@test_email = I18n.t('test_email')'
  end
end

By using the above code the @test_email.to_s text is not displayed (it seems to be blank) in the sent email and the I18n gem seems don't accomplish correctly what should be done. How can I solve the problem so to properly display the locale message in the "aimed" email body?


UPDATE for @volodymyr

The code you posted in your answer doesn't work for me. I tried also to add the following code to my config/locales/defaults/en.yml file:

en:
  hello: Test text!!!

The Test text!!! is still not displayed in the sent email (it is blank).

Upvotes: 2

Views: 556

Answers (1)

Volodymyr Rudyi
Volodymyr Rudyi

Reputation: 648

Here is example of working code(I`m using Rails 3.1.0 and ruby 1.9.3p0 (2011-10-30 revision 33570)):

# Fragment of mailer
def test_locale
    @test_email = I18n.t('hello')
    mail(:to => "<your_email_goes_here>", :subject => "test")
end

# Contents of test_locale.html.erb
String, retrieved from I18n: <%= @test_email %>

For testing I used Rails console:

MyMailer.test_locale.deliver

So you need to check if:

  • Erb template file name matches mailer`s method name
  • There is corresponding record in localization file
  • Variable names in mailer method and template file match
  • Folder name in "views" matches mailer name

UPDATE: Try to enclose string with quotes in localization file:

en:
    hello: "Some text here"

Upvotes: 1

Related Questions