Skip to content

Repository files navigation

Noticed

🎉 Notifications for your Ruby on Rails app.

Build StatusGem Version

Important

⚠️ Upgrading from V1? Read the Upgrade Guide!

Noticed is a gem that allows your application to send notifications of varying types, over various mediums, to various recipients. Be it a Slack notification to your own team when some internal event occurs or a notification to your user, sent as a text message, email, and real-time UI element in the browser, Noticed supports all of the above (at the same time)!

Noticed implements two top-level types of delivery methods:

  1. Individual Deliveries: Where each recipient gets their own notification
Show Example

Let’s use a car dealership as an example here. When someone purchases a car, a notification will be sent to the buyer with some contract details (“Congrats on your new 2024 XYZ Model...”), another to the car sales-person with different details (“You closed X deal; your commission is Y”), and another to the bank handling the loan with financial details (“New loan issued; amount $20,000...”). The event (the car being sold) necessitates multiple notifications being sent out to different recipients, but each contains its own unique information and should be separate from the others. These are individual deliveries.

  1. Bulk Deliveries: One notification for all recipients. This is useful for sending a notification to your Slack team, for example.
Show Example Let’s continue with the car-sale example here. Consider that your development team created the car-sales application that processed the deal above and sent out the notifications to the three parties. For the sake of team morale and feeling the ‘wins’, you may want to implement a notification that notifies your internal development team whenever a car sells through your platform. In this case, you’ll be notifying many people (your development team, maybe others at your company) but with the same content (“someone just bought a car through our platform!”). This is a bulk delivery. It’s generally a single notification that many people just need to be made aware of.

Bulk deliveries are typically used to push notifications to other platforms where users are managed (Slack, Discord, etc.) instead of your own.

Delivery methods we officially support:

Bulk delivery methods we support:

🎬 Screencast

Watch Screencast

🚀 Installation

Run the following command to add Noticed to your Gemfile:

bundleadd"noticed"

Generate then run the migrations:

rails noticed:install:migrations
rails db:migrate

📝 Usage

Noticed operates with a few constructs: Notifiers, delivery methods, and Notification records.

To start, generate a Notifier:

rails generate noticed:notifier NewCommentNotifier

Usage Contents

Notifier Objects

Notifiers are essentially the controllers of the Noticed ecosystem and represent an Event. As such, we recommend naming them with the event they model in mind — be it a NewSaleNotifier,ChargeFailureNotifier, etc.

Notifiers must inherit from Noticed::Event. This provides all of their functionality.

A Notifier exists to declare the various delivery methods that should be used for that event and any notification helper methods necessary in those delivery mechanisms. In this example we’ll deliver by :action_cable to provide real-time UI updates to users’ browsers, :email if they’ve opted into email notifications, and a bulk notification to :discord to tell everyone on the Discord server there’s been a new comment.

# ~/app/notifiers/new_comment_notifier.rbclassNewCommentNotifier < Noticed::Eventdeliver_by:action_cabledo |config|
config.channel="NotificationsChannel"config.stream=:some_streamenddeliver_by:emaildo |config|
config.mailer="CommentMailer"config.if=->{ !!recipient.preferences[:email]}endbulk_deliver_by:discorddo |config|
config.url="https://discord.com/xyz/xyz/123"config.json=->{{message: message,channel: :general}}endnotification_methodsdo# I18n helpersdefmessaget(".message")end# URL helpers are accessible in notifications# Don't forget to set your default_url_options so Rails knows how to generate urlsdefurluser_post_path(recipient,params[:post])endendend

For deeper specifics on setting up the :action_cable, :email, and :discord (bulk) delivery methods, refer to their docs: action_cable, email, and discord (bulk).

Delivery Method Configuration

Each delivery method can be configured with a block that yields a config object.

Procs/Lambdas will be evaluated when needed and symbols can be used to call a method.

When a lambda is passed, it will not pass any arguments and evaluates the Proc in the context of the Noticed::Notification

If you are using a symbol to call a method, we pass the notification object as an argument to the method. This allows you to access the notification object within the method. Your method must accept a single argument. If you don't need to use the object you can just use (*).

Show Example
classCommentNotifier < Noticed::Eventdeliver_by:iosdo |config|
config.format=:ios_formatconfig.apns_key=:ios_certconfig.key_id=:ios_key_idconfig.team_id=:ios_team_idconfig.bundle_identifier=Rails.application.credentials.dig(:ios,:bundle_identifier)config.device_tokens=:ios_device_tokensconfig.if=->{recipient.send_ios_notification?}enddefios_format(apn)apn.alert={title:,body: }apn.mutable_content=trueapn.content_available=trueapn.sound="notification.m4r"apn.custom_payload={url:,type: self.class.name,id: record.id,image_url: "" || image_url,params: params.to_json}enddefios_cert(*)Rails.application.credentials.dig(:ios,Rails.env.to_sym,:apns_token_cert)enddefios_key_id(*)Rails.application.credentials.dig(:ios,Rails.env.to_sym,:key_id)enddefios_team_id(*)Rails.application.credentials.dig(:ios,Rails.env.to_sym,:team_id)enddefios_bundle_id(*)Rails.application.credentials.dig(:ios,Rails.env.to_sym,:bundle_identifier)enddefios_device_tokens(notification)notification.recipient.ios_device_tokensenddefurlcomment_thread_path(record.thread)endendclassRecipient < ApplicationRecord# or whatever your recipient model ishas_many:ios_device_tokensdefsend_ios_notification?# some logicendend

More examples are in the docs for each delivery method.

Required Params

While explicit / required parameters are completely optional, Notifiers are able to opt in to required parameters via the required_params method:

classCarSaleNotifier < Noticed::Eventdeliver_by:email{ |c| c.mailer="BranchMailer"}# `record` is the Car record, `Branch` is the dealershiprequired_params:branch# To validate the `:record` param, add a validation since it is an association on the Noticed::Eventvalidates:record,presence: trueend

Which will validate upon any invocation that the specified parameters are present:

CarSaleNotifier.with(record: Car.last).deliver(Branch.last)#=> Noticed::ValidationError("Param `branch` is required for CarSaleNotifier")CarSaleNotifier.with(record: Car.last,branch: Branch.last).deliver(Branch.hq)#=> OK

Helper Methods

Notifiers can implement various helper methods, within a notification_methods block, that make it easier to render the resulting notification directly. These helpers can be helpful depending on where and how you choose to render notifications. A common use is rendering a user’s notifications in your web UI as standard ERB. These notification helper methods make that rendering much simpler:

<div><%@user.notifications.eachdo |notification| %><%=link_tonotification.message,notification.url%><%end%></div>

On the other hand, if you’re using email delivery, ActionMailer has its own full stack for setting up objects and rendering. Your notification helper methods will always be available from the notification object, but using ActionMailer’s own paradigms may fit better for that particular delivery method. YMMV.

URL Helpers

Rails url helpers are included in Notifiers by default so you have full access to them in your notification helper methods, just like you would in your controllers and views.

But don't forget, you'll need to configure default_url_options in order for Rails to know what host and port to use when generating URLs.

Rails.application.routes.default_url_options[:host]='localhost:3000'

Translations

We've also included Rails’ translate and t helpers for you to use in your notification helper methods. This also provides an easy way of scoping translations. If the key starts with a period, it will automatically scope the key under notifiers, the underscored name of the notifier class, and notification. For example:

From the above Notifier...

classNewCommentNotifier < Noticed::Event# ...notification_methodsdodefmessaget(".message")endend# ...end

Calling the message helper in an ERB view:

<%= @user.notifications.last.message %>

Will look for the following translation path:

# ~/config/locales/en.ymlen:
notifiers:
new_comment_notifier:
notification:
message: "Someone posted a new comment!"

Or, if you have your Notifier within another module, such as Admin::NewCommentNotifier, the resulting lookup path will be en.notifiers.admin.new_comment_notifier.notification.message (modules become nesting steps).

Tip: Capture User Preferences

You can use the if: and unless: options on your delivery methods to check the user's preferences and skip processing if they have disabled that type of notification.

For example:

classCommentNotifier < Noticed::Eventdeliver_by:emaildo |config|
config.mailer='CommentMailer'config.method=:new_commentconfig.if=->{recipient.email_notifications?}endend

If you would like to skip the delivery job altogether, for example if you know that a user doesn't support the platform and you would like to save resources by not enqueuing the job, you can use before_enqueue.

For example:

classIosNotifier < Noticed::Eventdeliver_by:iosdo |config|
# ...config.before_enqueue=->{throw(:abort)unlessrecipient.registered_ios?}endend

Tip: Extracting Delivery Method Configurations

If you want to reuse delivery method configurations across multiple Notifiers, you can extract them into a module and include them in your Notifiers.

# /app/notifiers/notifiers/comment_notifier.rbclassCommentNotifier < Noticed::EventincludeIosNotifierincludeAndroidNotifierincludeEmailNotifiervalidates:record,presence: trueend# /app/notifiers/concerns/ios_notifier.rbmoduleIosNotifierextendActiveSupport::Concernincludeddodeliver_by:iosdo |config|
config.device_tokens=->(recipient){recipient.notification_tokens.where(platform: :iOS).pluck(:token)}config.format=->(apn){apn.alert="Hello world"apn.custom_payload={url: root_url(host: "example.org")}}config.bundle_identifier=Rails.application.credentials.dig(:ios,:bundle_id)config.key_id=Rails.application.credentials.dig(:ios,:key_id)config.team_id=Rails.application.credentials.dig(:ios,:team_id)config.apns_key=Rails.application.credentials.dig(:ios,:apns_key)config.if=->{recipient.ios_notifications?}endendend

Shared Delivery Method Options

Each of these options are available for every delivery method (individual or bulk). The value passed may be a lambda, a symbol that represents a callable method, a symbol value, or a string value.

  • config.if — Intended for a lambda or method; runs after the wait if configured; cancels the delivery method if returns falsey
  • config.unless — Intended for a lambda or method; runs after the wait if configured; cancels the delivery method if returns truthy

The following are evaluated in the context of the Notification so it can be customize to the recipient:

  • config.wait — (Should yield an ActiveSupport::Duration) Delays the job that runs this delivery method for the given duration of time
  • config.wait_until — (Should yield a specific time object) Delays the job that runs this delivery method until the specific time specified
  • config.queue — Sets the ActiveJob queue name to be used for the job that runs this delivery method.

When using a symbol, the matching method must be defined inside the notification_methods block:

# app/notifiers/message_notifier.rbclassMessageNotifier < Noticed::Eventdeliver_by:delivery_methoddo |config|
config.queue=:queueendnotification_methodsdodefqueue"high_priority"endendend

📨 Sending Notifications

Following the NewCommentNotifier example above, here’s how we might invoke the Notifier to send notifications to every author in the thread about a new comment being added:

NewCommentNotifier.with(record: @comment,foo: "bar").deliver(@comment.thread.all_authors)

This instantiates a new NewCommentNotifier with params (similar to ActiveJob, any serializable params are permitted), then delivers notifications to all authors in the thread.

✨ The record: param is a special param that gets assigned to the record polymorphic association in the database. You should try to set the record: param where possible. This may be best understood as ‘the record/object this notification is about’, and allows for future queries from the record-side: “give me all notifications that were generated from this comment”.

This invocation will create a single Noticed::Event record and a Noticed::Notification record for each recipient. A background job will then process the Event and fire off a separate background job for each bulk delivery method and each recipient + individual-delivery-method combination. In this case, that’d be the following jobs kicked off from this event:

  • A bulk delivery job for :discord bulk delivery
  • An individual delivery job for :action_cable method to the first thread author
  • An individual delivery job for :email method to the first thread author
  • An individual delivery job for :action_cable method to the second thread author
  • An individual delivery job for :email method to the second thread author
  • Etc...

Tip: Define recipients inside the notifier

Recipients can also be computed inside a notifier:

classNewCommentNotifier < ApplicationNotifierrecipients->{params[:record].thread.all_authors}# orrecipientsdoparams[:record].thread.all_authorsend# orrecipients:fetch_recipientsdeffetch_recipients# ...endend

This makes the code for sending a notification neater:

NewCommentNotifier.with(record: @comment,foo: "bar").deliver

Custom Noticed Model Methods

In order to extend the Noticed models you'll need to use a concern and a to_prepare block:

# config/initializers/noticed.rbmoduleNotificationExtensionsextendActiveSupport::Concernincludeddobelongs_to:organizationscope:filter_by_type,->(type){where(type:)}scope:exclude_type,->(type){where.not(type:)}end# You can also add instance methods hereendRails.application.config.to_preparedo# You can extend Noticed::Event or Noticed::Notification hereNoticed::Event.includeEventExtensionsNoticed::Notification.includeNotificationExtensionsend

The NotificationExtensions class could be separated into it's own file and live somewhere like app/models/concerns/notification_extensions.rb.

If you do this, the to_prepare block will need to be in application.rb instead of an initializer.

# config/application.rbmoduleMyAppclassApplication < Rails::Application# ...config.to_preparedoNoticed::Event.includeEventExtensionsNoticed::Notification.includeNotificationExtensionsendendend

✅ Best Practices

Renaming Notifiers

If you rename a Notifier class your existing data and Noticed setup may break. This is because Noticed serializes the class name and sets it to the type column on the Noticed::Event record and the type column on the Noticed::Notification record.

When renaming a Notifier class you will need to backfill existing Events and Notifications to reference the new name.

Noticed::Event.where(type: "OldNotifierClassName").update_all(type: NewNotifierClassName.name)# andNoticed::Notification.where(type: "OldNotifierClassName::Notification").update_all(type: "#{NewNotifierClassName.name}::Notification")

🚛 Delivery Methods

The delivery methods are designed to be modular so you can customize the way each type gets delivered.

For example, emails will require a subject, body, and email address while an SMS requires a phone number and simple message. You can define the formats for each of these in your Notifier and the delivery method will handle the processing of it.

Individual delivery methods:

Bulk delivery methods:

No Delivery Methods

It’s worth pointing out that you can have a fully-functional and useful Notifier that has no delivery methods. This means that invoking the Notifier and ‘sending’ the notification will only create new database records (no external surfaces like email, sms, etc.). This is still useful as it’s the database records that allow your app to render a user’s (or other object’s) notifications in your web UI.

So even with no delivery methods set, this example is still perfectly available and helpful:

<div><%@user.notifications.eachdo |notification| %><%=link_tonotification.message,notification.url%><%end%></div>

Sending a notification is entirely an internal-to-your-app function. Delivery methods just get the word out! But many apps may be fully satisfied without that extra layer.

Fallback Notifications

A common pattern is to deliver a notification via a real (or real-ish)-time service, then, after some time has passed, email the user if they have not yet read the notification. You can implement this functionality by combining multiple delivery methods, the wait option, and the conditional if / unless option.

classNewCommentNotifier < Noticed::Eventdeliver_by:action_cabledeliver_by:emaildo |config|
config.mailer="CommentMailer"config.wait=15.minutesconfig.unless=->{read?}endend

Here a notification will be created immediately in the database (for display directly in your app’s web interface) and sent via ActionCable. If the notification has not been marked read after 15 minutes, the email notification will be sent. If the notification has already been read in the app, the email will be skipped.

A note here: notifications expose a #mark_as_read method, but your app must choose when and where to call that method.

You can mix and match the options and delivery methods to suit your application specific needs.

🚚 Custom Delivery Methods

If you want to build your own delivery method to deliver notifications to a specific service or medium that Noticed doesn’t (or doesn’t yet) support, you’re welcome to do so! To generate a custom delivery method, simply run

rails generate noticed:delivery_method Discord

This will generate a new ApplicationDeliveryMethod and DeliveryMethods::Discord class inside the app/notifiers/delivery_methods folder, which can be used to deliver notifications to Discord.

classDeliveryMethods::Discord < ApplicationDeliveryMethod# Specify the config options your delivery method requires in its config blockrequired_options# :foo, :bardefdeliver# Logic for sending the notificationendend

You can use the custom delivery method thus created by adding a deliver_by line with a unique name and class option in your notification class.

classMyNotifier < Noticed::Eventdeliver_by:discord,class: "DeliveryMethods::Discord"end
Turbo Stream Custom Delivery Method Example

A common custom delivery method in the Rails world might be to Delivery to the web via turbo stream.

Note: This example uses custom methods that extend the Noticed::Notification class.

See the Custom Noticed Model Methods section for more information.

# app/notifiers/delivery_methods/turbo_stream.rbclassDeliveryMethods::TurboStream < ApplicationDeliveryMethoddefdeliverreturnunlessrecipient.is_a?(User)notification.broadcast_update_to_bellnotification.broadcast_replace_to_index_countnotification.broadcast_prepend_to_index_listendend
# app/models/concerns/noticed/notification_extensions.rbmoduleNoticed::NotificationExtensionsextendActiveSupport::Concerndefbroadcast_update_to_bellbroadcast_update_to("notifications_#{recipient.id}",target: "notification_bell",partial: "navbar/notifications/bell",locals: {user: recipient})enddefbroadcast_replace_to_index_countbroadcast_replace_to("notifications_index_#{recipient.id}",target: "notification_index_count",partial: "notifications/notifications_count",locals: {count: recipient.reload.notifications_count,unread: recipient.reload.unread_notifications_count})enddefbroadcast_prepend_to_index_listbroadcast_prepend_to("notifications_index_list_#{recipient.id}",target: "notifications",partial: "notifications/notification",locals: {notification: self})endend

Delivery methods have access to the following methods and attributes:

  • event — The Noticed::Event record that spawned the notification object currently being delivered
  • record — The object originally passed into the Notifier as the record: param (see the ✨ note above)
  • notification — The Noticed::Notification instance being delivered. All notification helper methods are available on this object
  • recipient — The individual recipient object being delivered to for this notification (remember that each recipient gets their own instance of the Delivery Method #deliver)
  • config — The hash of configuration options declared by the Notifier that generated this notification and delivery
  • params — The parameters given to the Notifier in the invocation (via .with())

Validating config options passed to Custom Delivery methods

The presence of delivery method config options are automatically validated when declaring them with the required_options method. In the following example, Noticed will ensure that any Notifier using deliver_by :email will specify the mailer and method config keys:

classDeliveryMethods::Email < Noticed::DeliveryMethodrequired_options:mailer,:methoddefdeliver# ...method=config.methodendend

If you’d like your config options to support dynamic resolution (set config.foo to a lambda or symbol of a method name etc.), you can use evaluate_option:

classNewSaleNotifier < Noticed::Eventdeliver_by:whats_appdo |config|
config.day=->{is_tuesday?"Tuesday" : "Not Tuesday"}endendclassDeliveryMethods::WhatsApp < Noticed::DeliveryMethodrequired_options:daydefdeliver# ...config.day#=> #<Proc:0x000f7c8 (lambda)>evaluate_option(:day)#=> "Tuesday"endend

Callbacks

Callbacks for delivery methods wrap the actual delivery of the notification. You can use before_deliver, around_deliver and after_deliver in your custom delivery methods.

classDeliveryMethods::Discord < Noticed::DeliveryMethodafter_deliverdo# Do whatever you wantendend

📦 Database Model

The Noticed database models include several helpful features to make working with notifications easier.

Notification

Class methods/scopes

(Assuming your user has_many :notifications, as: :recipient, class_name: "Noticed::Notification")

Sorting notifications by newest first:

@user.notifications.newest_first

Query for read or unread notifications:

user.notifications.readuser.notifications.unread

Marking all notifications as read or unread:

user.notifications.mark_as_readuser.notifications.mark_as_unread

Instance methods

Mark notification as read / unread:

@notification.mark_as_read@notification.mark_as_read!@notification.mark_as_unread@notification.mark_as_unread!

Check if read / unread:

@notification.read?@notification.unread?

Associating Notifications

Adding notification associations to your models makes querying, rendering, and managing notifications easy (and is a pretty critical feature of most applications).

There are two ways to associate your models to notifications:

  1. Where your object has_many notifications as the recipient (who you sent the notification to)
  2. Where your object has_many notifications as the record (what the notifications were about)

In the former, we’ll use a has_many to :notifications. In the latter, we’ll actually has_many to :events, since records generate notifiable events (and events generate notifications).

We can illustrate that in the following:

classUser < ApplicationRecordhas_many:notifications,as: :recipient,dependent: :destroy,class_name: "Noticed::Notification"end# All of the notifications the user has been sent# @user.notifications.each { |n| render(n) }classPost < ApplicationRecordhas_many:noticed_events,as: :record,dependent: :destroy,class_name: "Noticed::Event"has_many:notifications,through: :noticed_events,class_name: "Noticed::Notification"end# All of the notification events this post generated# @post.notifications

ActiveJob Parent Class

Noticed uses its own Noticed::ApplicationJob as the base job for all notifications. In the event that you would like to customize the parent job class, there is a parent_class attribute that can be overridden with your own class. This should be done in a noticed.rb initializer.

Noticed.parent_class="ApplicationJob"

Handling Deleted Records

Generally we recommend using a dependent: ___ relationship on your models to avoid cases where Noticed Events or Notifications are left lingering when your models are destroyed. In the case that they are or data becomes mis-matched, you’ll likely run into deserialization issues. That may be globally alleviated with the following snippet, but use with caution.

classApplicationJob < ActiveJob::Basediscard_onActiveJob::DeserializationErrorend

Customizing the Database Models

You can modify the database models by editing the generated migrations.

One common adjustment is to change the IDs to UUIDs (if you're using UUIDs in your app).

You can also add additional columns to the Noticed::Event and Noticed::Notification models.

# This migration comes from noticed (originally 20231215190233)classCreateNoticedTables < ActiveRecord::Migration[7.1]defchangecreate_table:noticed_events,id: :uuiddo |t|
t.string:typet.belongs_to:record,polymorphic: true,type: :uuidt.jsonb:params# Custom Fieldst.string:organization_id,type: :uuid,as: "((params ->> 'organization_id')::uuid)",stored: truet.virtual:action_type,type: :string,as: "((params ->> 'action_type'))",stored: truet.virtual:url,type: :string,as: "((params ->> 'url'))",stored: truet.timestampsendcreate_table:noticed_notifications,id: :uuiddo |t|
t.string:typet.belongs_to:event,null: false,type: :uuidt.belongs_to:recipient,polymorphic: true,null: false,type: :uuidt.datetime:read_att.datetime:seen_att.timestampsendadd_index:noticed_notifications,:read_atendend

The custom fields in the above example are stored as virtual columns. These are populated from values passed in the params hash when creating the notifier.

🙏 Contributing

This project uses Standard for formatting Ruby code. Please make sure to run standardrb before submitting pull requests.

Running tests against multiple databases locally:

DATABASE_URL=sqlite3:noticed_test rails test
DATABASE_URL=trilogy://root:@127.0.0.1/noticed_test rails test
DATABASE_URL=postgres://127.0.0.1/noticed_test rails test

📝 License

The gem is available as open source under the terms of the MIT License.

About

Notifications for Ruby on Rails applications

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages