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

后端 未结 7 1901
说谎
说谎 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:58

    The problem with the mentioned plugins are that they don't work in all situations, for example doing User.human_name or User.human_attribute_name(...) will not translate correctly. The following is the easiest and guaranteed method to work:

    stick this somewhere (in initializers or a plugin):

      module I18nActionMailer
        def self.included(base)
          base.class_eval do
            include InstanceMethods
            alias_method_chain :create!, :locale
          end
        end
    
        module InstanceMethods
          def create_with_locale!(method_name, *parameters)
            original_locale = I18n.locale
            begin
              create_without_locale!(method_name, *parameters)
            ensure
              I18n.locale = original_locale
            end
          end
        end
      end
    
      ActionMailer::Base.send(:include, I18nActionMailer)
    

    and then in your mailer class start your method by setting the desired locale, for example:

      def welcome(user)
        I18n.locale = user.locale
        # etc.
      end
    

提交回复
热议问题