Noticed is a gem designed to simplify managing user notifications. While it might be overkill for today’s task, it shines when you need to send multiple types of notifications (email, push, Slack) to various users, which we will address tomorrow.
For today’s example, we’ll set up email notifications for new user signups. Let’s dive in:
First, add noticed to your Gemfile and install it:
bundle add noticed
rails noticed:install:migrations
rails db:migrate
This prepares your app for notifications by creating a table to track events and notifications. For example, when a new user signs up, you could notify all admins in your system—creating one event and multiple notifications.
Next, generate a standard Rails mailer to handle email notifications. The key difference here is following Noticed
conventions for parameters:
rails generate mailer UserMailer new_user_signed_up
Here’s the mailer:
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
def new_user_signed_up
@recipient = params[:recipient] # Provided by Noticed
@new_user = params[:record] # The subject of the notification
mail to: recipient.email_address
end
end
While you could call the mailer directly, a Noticed
notifier offers more flexibility. Generate it like so:
rails generate noticed:notifier NewUserNotifier
Here’s how to configure the notifier to use your mailer:
# app/notifiers/new_user_notifier.rb
class NewUserNotifier < ApplicationNotifier
deliver_by :email do |config|
config.mailer = "UserMailer"
config.method = "new_user_signed_up"
end
end
Finally, use the notifier in your controller to send notifications to all admin users when a new user signs up:
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def create
# …
if user.save
NewUserNotifier.with(record: user).deliver(Users.admins)
# redirect_to etc.
end
end
end
With this setup, you’re tracking notifications in the database and sending emails seamlessly. Noticed handles the heavy lifting, making it easier to extend your notifications later.
Tomorrow, we’ll enhance this setup by adding a delivery option for native web-based push notifications. Stay tuned!