Notifications for Ruby on Rails applications
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:
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.
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:
Run the following command to add Noticed to your Gemfile:
bundle add "noticed"Generate then run the migrations:
rails noticed:install:migrations
rails db:migrateNoticed operates with a few constructs: Notifiers, delivery methods, and Notification records.
To start, generate a Notifier:
rails generate noticed:notifier NewCommentNotifierNotifiers 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.
…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).
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 (*).
…More examples are in the docs for each delivery method.
While explicit / required parameters are completely optional, Notifiers are able to opt in to required parameters via the required_params method:
class CarSaleNotifier < Noticed::Event
deliver_by :email { |c| c.mailer = "BranchMailer" }
# `record` is the Car record, `Branch` is the dealership
required_params :branch
# To validate the `:record` param, add a validation since it is an association on the Noticed::Event
validates :record, presence: true
endWhich 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)
#=> OKNotifiers 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:
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.
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'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...
class NewCommentNotifier < Noticed::Event
# ...
notification_methods do
def message
t(".message")
end
end
# ...
endCalling the message helper in an ERB view:
<%= @user.notifications.last.message %>Will look for the following translation path:
# ~/config/locales/en.yml
en:
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).
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:
class CommentNotifier < Noticed::Event
deliver_by :email do |config|
config.mailer = 'CommentMailer'
config.method = :new_comment
config.if = ->{ recipient.email_notifications? }
end
endIf 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:
class IosNotifier < Noticed::Event
deliver_by :ios do |config|
# ...
config.before_enqueue = ->{ throw(:abort) unless recipient.registered_ios? }
end
endIf you want to reuse delivery method configurations across multiple Notifiers, you can extract them into a module and include them in your Notifiers.
…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 falseyconfig.unless — Intended for a lambda or method; runs after the wait if configured; cancels the delivery method if returns truthyThe 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 timeconfig.wait_until — (Should yield a specific time object) Delays the job that runs this delivery method until the specific time specifiedconfig.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.rb
class MessageNotifier < Noticed::Event
deliver_by :delivery_method do |config|
config.queue = :queue
end
notification_methods do
def queue
"high_priority"
end
end
endFollowing 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
No open issues yet, or sync has not completed.