20
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Devise で送信するメールのローカライズ

20
Last updated at Posted at 2014-04-14

Deviseを使って送信されるメールのローカライズしたい。
けど、多言語化ファイル(config/locales以下のファイル)を使ったローカライズだと自由度が効かない。

要するに言語ごとにメールのテンプレートを分けたい!

という方のための方法。

Devise の helper を上書き

結論から言うと、テンプレートファイルを呼び出す順番を書き換える。
以下を config/initializers/devise.rb に追記する。

config/initializers/devise.rb
module Devise
  module Mailers
    module Helpers
    protected
      def template_paths
        template_path = _prefixes.dup
        template_path.unshift "#{@devise_mapping.scoped_path}/mailer" if self.class.scoped_views?
        template_path.unshift "#{@devise_mapping.scoped_path}/mailer/#{I18n.default_locale}" if self.class.scoped_views?
        template_path
      end
    end
  end
end

ポイントは、template_path の先頭にロケール情報を含んだパスを追加する。

例えば、rails generate devise Userusers というスコープを作成していて、
標準ロケールを日本語に設定している場合(config.i18n.default_locale = :ja

追記前
template_paths # => ['users/mailer', 'devise/mailer']
追記後
template_paths # => ['users/mailer/ja', 'users/mailer', 'devise/mailer']

になる。
これで、Devise がメールを送る場合に探し出すテンプレートファイルの順番が

  1. app/views/users/mailer/ja
  2. app/views/users/mailer
  3. devise/mailer

に変わるので、ja ファイルの下に日本語で書かれたテンプレートファイルを置く。

これで、言語ごとにテンプレートファイルを分けることができる。

20
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?