Jonathan Bennett

Custom Web Push Delivery Method in Noticed

Currently, there’s no built-in support for web push notifications in Rails. Fortunately, we’ve already done most of the groundwork to integrate it seamlessly with Noticed.

To make this work, we’ll create a custom delivery method for web push notifications. Our goal is to end up with a configuration like this:

class NewUserNotifier < ApplicationNotifier
  deliver_by :email # Existing delivery method

  deliver_by :web_push, class: "DeliveryMethods::WebPush" do |config|
	config.json = -> do
	  {
		title: "New user signed up",
		body: "This is the body of the notification",
		url: user_profile_path(record),
		badge_count: recipient.notifications.unread.count
	  }
	end
  end
end

Creating the Custom Delivery Method

The custom delivery method allows us to set the notification’s title and optionally include additional data such as the body, URL, and badge count using the configuration:

# app/models/delivery_methods/web_push.rb
module DeliveryMethods
  class WebPush < Noticed::DeliveryMethod
	required_options :json # 1

	def deliver
	  data = notification.instance_exec(&config[:json]) # 2
	  recipient.web_push_subscriptions.each do |subscription|
		subscription.deliver_payload(data)
	  end
	end
  end
end

Here’s what’s happening:

  1. required_options :json ensures that the deliver_by configuration must include a json key.
  2. instance_exec(&config[:json]) evaluates the json lambda in the context of the notification class, allowing it to generate the data dynamically for each notification.

Since we’ve already implemented the system for sending notifications, integrating with Noticed only requires passing the necessary data hash for the web push delivery. This allows Noticed to handle the delivery seamlessly while keeping your code modular and flexible.