Rails2.0.2のヘルプ、中身拝見(4)
Ruby January 2nd, 2008
備忘録というかRails2になってからドキュメントが改訂されているケースが少ないことへの腹いせに始めたものの、コードを全然書かないし成果が何もないので飽きてきたヘルプ拝見だが、乗りかけた船ということで続けてみる。
今度はgenerateでmailerを指定してみよう。
mailer
実際の例:
$ ruby script/generate mailer Notification signup forgot_password invoice
exists app/models/
create app/views/notification
exists test/unit/
create test/fixtures/notification
create app/models/notification.rb
create test/unit/notification_test.rb
create app/views/notification/signup.erb
create test/fixtures/notification/signup
create app/views/notification/forgot_password.erb
create test/fixtures/notification/forgot_password
create app/views/notification/invoice.erb
create test/fixtures/notification/invoice
Notificationという名前のmailerを指定すると、新規にmailerとそのビューのスタブを作成してくれる。といっても、コントローラには特に何も追加されず、modelとviewのみ何かが作成されているので、ブラウザですぐに変更を確認できるわけではない。
ここで作成されたモデルには、ちょっと不気味なルールが適用される。先ほど作成したlistというコントローラを下のように変更して、Notificationモデルを実装してみよう。
model以下に作成されたnotification.rbのsignupというメソッドのみ変更してみた。
$ cat app/models/notification.rb
class Notification < ActionMailer::Base
def signup(sent_at = Time.now)
@subject = 'Notification#signup'
@body = {}
@recipients = 'root@localhost'
@from = 'user@localhost'
@sent_on = sent_at
@headers = {}
end
def forgot_password(sent_at = Time.now)
@subject = 'Notification#forgot_password'
@body = {}
@recipients = ''
@from = ''
@sent_on = sent_at
@headers = {}
end
def invoice(sent_at = Time.now)
@subject = 'Notification#invoice'
@body = {}
@recipients = ''
@from = ''
@sent_on = sent_at
@headers = {}
end
end
signupというメソッドが呼び出されたら標題や本文、Fromや宛先が指定されたものになるように変更している。ご覧の通り、generate mailerで作成されたmodelはActionMailerクラスを継承している。続いてこちらをコントローラから呼び出してみる。以前作成したコントローラを利用する。
$ cat app/controllers/list_controller.rb
class ListController < ApplicationController
def index
Notification.deliver_signup()
end
def create
end
def edit
end
def delete
end
end
奇妙なことに、実装した覚えのない「deliver_signup」というメソッドが無造作に呼び出されている。また、Notificationクラスもいきなり呼び出してしまっているわけだが、model上のクラスはこうして呼び出すことが出来るのがRailsの規則のようだ。
この「deliver_signup」というメソッドは、正直ちょっと面食らってしまったのだが、動作としてはsignupメソッドのことを指している。その証拠に、これを実行するとログにはメールが配信されたと出力される。ようするに、ActionMailerを利用したメール送信では、deliver_付きのメソッドが呼び出されると、deliver_以下の名前のメソッドが実行され、メール送信に必要な情報はそちらで定義されたものが利用されることになっているということのようだ。
メール送信機能を実装する際のヘルパー、generate mailerの使い方はざっとこんな感じ。