How can I send emails in Rails 3 using the recipient's locale?

后端 未结 7 1822
说谎
说谎 2021-02-03 23:44

How can I send mails in a mailer using the recipient\'s locale. I have the preferred locale for each user in the database. Notice this is different from the current locale (I18n

7条回答
  •  无人共我
    2021-02-03 23:56

    None of the above is really working since the version 3 to translate both subject and content and be sure that the locale is reseted back to the original one... so I did the following (all mailer inherit from that class:

    class ResourceMailer < ActionMailer::Base
    
      def mail(headers={}, &block)
        I18n.locale = mail_locale
        super
      ensure
        reset_locale
      end
    
      def i18n_subject(options = {})
        I18n.locale = mail_locale
        mailer_scope = self.class.mailer_name.gsub('/', '.')
        I18n.t(:subject, options.merge(:scope => [mailer_scope, action_name], :default => action_name.humanize))
      ensure
        reset_locale
      end  
    
      def set_locale(locale)
        @mail_locale = locale
      end
    
      protected
    
      def mail_locale
        @mail_locale || I18n.locale
      end
    
      def reset_locale
        I18n.locale = I18n.default_locale
      end
    
    end
    

    You just need to set the locale before you call the mail() method:

    set_locale @user.locale
    

    You can use the i18n_subject method which scope the current path so everything is structured:

    mail(:subject => i18n_subject(:name => @user.name)
    

提交回复
热议问题