railsチュートリアル第7版を始めて1か月の初心者です。
今回はRailsチュートリアルで作成したアプリにフォロワー通知機能を追加するための方法を説明していきたいと思います。
フォロワー通知編は今回のメーラー作成、次回の通知機能のON/OFF切替実装の全2回を予定しています。
目次
実装した機能詳細
- フォローされたらメールで通知がくる
- フォロー外された場合は通知は特になし
- メールにフォロワーを見るページのリンクなどは一切つけない
※今回は新たにrails generateすることなく実装を進める
私は以上のような最低限の機能を実装しました。
メール送信のためのメソッドを作成
/app/mailers/user_mailer.rb
def follow_notification(user, follower)
@user = user
@follower = follower
mail to: user.email, subject: "#{@follower.name} started following you"
end
上記のコードをもともとあったメーラーのファイルに追加しました。
メール本文の作成
HTMLとテキストのメール本文を作成するために
/app/views/user_mailer/follow_notification.html.erb
と/app/views/user_mailer/follow_notification.text.erb
を新たに作成し、以下のコードを追加します。
メール本文(HTML)
/app/views/user_mailer/follow_notification.html.erb
<h1>You are followed</h1>
<p>Hi <%= @user.name %>,</p>
<p>
<%= @follower.name %> started following you!
</p>
メール本文(text)
/app/views/user_mailer/follow_notification.text.erb
You are followed
Hi <%= @user.name %>,
<%= @follower.name %> started following you!
テスト用ビューの追加
/test/mailers/previews/user_mailer_preview.rb
# Preview this email at
# http://localhost:3000/rails/mailers/user_mailer/follow_notification
def follow_notification
user = User.first
follower = User.second
UserMailer.follow_notification(user, follower)
end
メーラーのテストの作成
/test/mailers/user_mailer_test.rb
test "follow_notification" do
user = users(:michael)
follower = users(:inactive)
mail = UserMailer.follow_notification(user, follower)
assert_equal "#{follower.name} started following you", mail.subject
assert_equal [user.email], mail.to
assert_equal ["from@example.com"], mail.from
assert_match user.name, mail.body.encoded
assert_match follower.name, mail.body.encoded
end
from@example.com
の部分は自分で設定した送信用メールアドレスにすることを忘れないようにしてください。
メール送信用メソッドを使う場所に追加
先程作成したメソッドを使用するためのコードを記載します。
/app/models/user.rb
...
# ユーザーをフォローする
def follow(other_user)
following << other_user unless self == other_user
if other_user.follow_notification
UserMailer.follow_notification(other_user, self).deliver_now
end
end
...
以上のコードを追加することによって最低限フォロワー通知をすることができるようになります。
次回の記事では、フォロワー通知のON/OFFができるように実装していきます。
参考