Ruby on Rails 3.2 Mailer,本地化邮件主题字段 [英] Ruby on Rails 3.2 Mailer, localize mail subject field

查看:60
本文介绍了Ruby on Rails 3.2 Mailer,本地化邮件主题字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用RoR 3.2编写邮件程序,该程序可以发送应根据用户语言进行本地化的邮件。我设法呈现正确的本地化视图,但是在某些需要更改语言环境的字段(例如主题)上遇到了一些困难。
在发送电子邮件之前,我已经阅读了一些反对更改语言环境的帖子。用户使用多种语言,这意味着每次向用户发送电子邮件时都会更改我的区域设置。

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?

下面是一个摘要:

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

我的观点

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

简而言之,在这种情况下,我想使用@locale来本地化:subject,而不是通过运行:I18n.locale = locale

In short, in this case, I'd like to localize the :subject using the @locale, but not by running: I18n.locale = locale

推荐答案

可以临时更改全局语言环境。有一个方便的I18n.with_locale方法。

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

在区域设置中:

en:
  auth_mailer:
    invite:
      subject: Invitation

这篇关于Ruby on Rails 3.2 Mailer,本地化邮件主题字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆