ruby 31 lines · 6 steps

Multi-channel notifications with Noticed in Rails

A single notifier class fans one comment event out to the database, email, and a live WebSocket channel.

Explained by highlit
1class NewCommentNotifier < ApplicationNotifier
2 deliver_by :database
3 
4 deliver_by :email do |config|
5 config.mailer = "CommentMailer"
6 config.method = :new_comment
7 config.if = -> { recipient.email_notifications? }
8 end
9 
10 deliver_by :action_cable do |config|
11 config.channel = "NotificationsChannel"
12 config.stream = -> { recipient }
13 config.message = -> { { unread_count: recipient.notifications.unread.count } }
14 end
15 
16 notification_methods do
17 def message
18 t(".message", commenter: comment.author.name, post: comment.post.title)
19 end
20 
21 def url
22 post_path(comment.post, anchor: "comment-#{comment.id}")
23 end
24 end
25 
26 required_param :comment
27 
28 def comment
29 params[:comment]
30 end
31end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Declaring multiple deliver_by methods lets one event reach several channels without duplicating logic.
  2. 2Lambdas evaluated in the notifier context let per-delivery config react to the recipient and payload.
  3. 3Centralizing message and url in the notifier keeps every channel's copy consistent.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Multi-channel notifications with Noticed in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code