acts_as_authenticatedの使い方 - その2

ActionMailerの設定

前回のacts_as_authenticatedプラグインを使って、ActionMailerの設定を行う。acts_as_authenticatedプラグインが用意しているジェネレータのうち、authenticated_mailerを実行する。

$ ./script/generate authenticated_mailer user
      exists  app/models/
      create  app/views/user_notifier
      exists  test/unit/
      create  app/models/user_notifier.rb
      create  app/models/user_observer.rb
      create  test/unit/user_notifier_test.rb
      create  app/views/user_notifier/activation.rhtml
      create  app/views/user_notifier/signup_notification.rhtml

ここで生成されるuser_observer.rbはuserモデル(app/model/user.rb)のオブザーバ用コードで、userモデルに対するCRUD操作に対して自動的に呼び出されるハンドラを定義している。authenticated_mailerがデフォルトで生成するコードは以下の通り。

class UserObserver < ActiveRecord::Observer
  def after_create(user)
    UserNotifier.deliver_signup_notification(user)
  end

  def after_save(user)
    UserNotifier.deliver_activation(user) if user.recently_activated?
  end
end

デザインパターンで言うところのObserverパターンと同じで、あるオブジェクトの状態が変化した時に、それに依存するオブジェクトにそのことが自動的に通知される仕組みを実装している。
このオブザーバの存在をActiveRecordに知らせるために、config/environment.rbに以下のコードを追加する。これはコードブロック Rails::Initializer.run do |config| の中に書く。

config.active_record.observers = :user_observer

UserObserverに対して定義できるコールバックは、こちらのページに記載されている。

authenticated_mailerジェネレータで生成したコードでは日本語のメールをそのまま扱うことができないので、メールをiso-2022-jp化するためのプラグインであるActiveHeartを組み込んでおく。ActiveHeartのうち、日本語メールの部分だけを利用したいので、script/plugin installコマンドは使わずに、必要なファイルだけをlibディレクトリにダウンロードする。

wget http://svn.rails2u.com/public/plugins/trunk/active_heart/lib/iso2022jp_mailer.rb

次にmodel/user_notifier.rbのクラスを宣言のところで、以下のようにActionMailer::Baseではなく、Iso2022jpMailerからサブクラス化するように変更する。

#class UserNotifier < ActionMailer::Base  #コメント化
class UserNotifier < Iso2022jpMailer

また、UserNotifierの各メソッドを以下のように修正する。

        :
        :
  def signup_notification(user)
    setup_email(user)
    @subject    += 'Please activate your new account'
#    @body[:url]  = "http://YOURSITE/account/activate/#{user.activation_code}"
    @body[:url]  = "http://localhost:3000/account/activate/zzzzzzzzz"
  end

  def activation(user)
    setup_email(user)
    @subject    += 'Your account has been activated!'
#    @body[:url]  = "http://YOURSITE/"
    @body[:url]  = "http://localhost:3000/"
  end

  protected
  def setup_email(user)
    @recipients  = "#{user.email}"
#    @from        = "ADMINEMAIL"
    @from        = "自分のメールアドレス"
#    @subject     = "[YOURSITE] "
    @subject     = "[localhost:3000] "
    @sent_on     = Time.now
    @body[:user] = user
  end
end

ActionMailerはメールの送信のためにいくつかの設定を予め実施しておかなければならない。以下の設定はconfig/environment.rbに追加しておく。

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "iso-2022-jp"

ActionMailer::Base.smtp_settings = {
  :address => "自分のSMTPサーバのアドレス名",
  :port => 25,
  :domain => "自分のドメイン名(HELOドメインのこと)",
  :authentication => :login,
  :user_name => "自分のSMTPサーバのユーザアカウント名",
  :password => "自分のSMTPサーバのパスワード",
}

そしてscript/consoleから、以下のようにUserクラスを初期化して、deliver_signup_notificationを呼び出すと、自分のメールアドレスにメールが送信されるはずだ。

>> user = User.new(:email=>"自分のメールアドレス", :login=>"登録する名前(半角)", :password=>"登録するパスワード(半角)")
>> UserNotifier.deliver_signup_notification(user)

到着したメールは以下のようになっている。

Your account has been created.

  Username: yourname
  Password: yourpass

Visit this url to activate your account:

  http://localhost:3000/account/activate/zzzzzzzzz

ここまでで、メール送信の設定は終了したことになるが、メールの中身も日本語にしてみよう。以下のようにapp/views/user_notifier/signup_notification.rhtmlを日本語に書き換える。

アカウントが生成されました。

  Username: <%= @user.login %>
  Password: <%= @user.password %>

以下のURLにアクセスしてアカウントをアクティベートしてください。

  <%= @url %>

これで再度メールを送信すれば、日本語のiso-2022-jpになったメールが到着するはずだ。