Jos*_*ose 24 actionmailer internationalization ruby-on-rails-3
如何使用收件人的区域设置在邮件程序中发送邮件.我有数据库中每个用户的首选语言环境.请注意,这与当前区域设置(I18n.locale)不同,只要当前用户不必是收件人即可.所以困难的是在不改变I18n.locale的情况下在不同的语言环境中使用邮件程序:
def new_follower(user, follower)
@follower = follower
@user = user
mail :to=>@user.email
end
Run Code Online (Sandbox Code Playgroud)
在mail:to => ...之前使用I18n.locale = @ user.profile.locale将解决邮件程序问题,但会改变线程其余部分的行为.
Mig*_*raz 40
我相信这样做的最好方法是使用优秀的方法I18n.with_locale,它允许你暂时改变I18n.locale一个块内部,你可以像这样使用它:
def new_follower(user, follower)
@follower = follower
@user = user
I18n.with_locale(@user.profile.locale) do
mail to: @user.email
end
end
Run Code Online (Sandbox Code Playgroud)
并且它会更改区域设置只是为了发送电子邮件,在块结束后立即更改回来.
资料来源:http://www.rubydoc.info/docs/rails/2.3.8/I18n.with_locale
这个答案是一个肮脏的黑客,忽略了I18n的with_locale方法,这是另一个答案.原始答案(有效,但你不应该使用它)如下.
又快又脏:
class SystemMailer < ActionMailer::Base
def new_follower(user, follower)
@follower = follower
@user = user
using_locale(@user.profile.locale){mail(:to=>@user.email)}
end
protected
def using_locale(locale, &block)
original_locale = I18n.locale
I18n.locale = locale
return_value = yield
I18n.locale = original_locale
return_value
end
end
Run Code Online (Sandbox Code Playgroud)
这个简单的插件是为 Rails 2 开发的,但似乎也适用于 Rails 3。
http://github.com/Bertg/i18n_action_mailer
使用它您可以执行以下操作:
def new_follower(user, follower)
@follower = follower
@user = user
set_locale user.locale
mail :to => @user.email, :subject => t(:new_follower_subject)
end
Run Code Online (Sandbox Code Playgroud)
然后使用用户的区域设置翻译主题和邮件模板。
| 归档时间: |
|
| 查看次数: |
9386 次 |
| 最近记录: |