Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

actionmailer - Ruby on Rails 3.2 Mailer, localize mail subject field

I'm currently writing a mailer in RoR 3.2 that would send out mails that should be localized based on a users' language. I managed to render the correct localized views but I'm having some difficulties with some fields that require changing the locale (like the subject). I've already read some posts that are against changing the locale before sending the email. The users have many different languages and that would mean changing my locale every time a user is sent an email.

I know that it would be possible to change the locale, send the email, change back the locale. This doesn't feel like the rails way. Is there a correct way of doing this?

Here's 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'd like to localize the :subject using the @locale, but not by running: I18n.locale = locale

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is OK to change the global locale temporarily. There is a handy I18n.with_locale method for that. Also ActionMailer automatically translates a subject.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...