Push Notifications In Ruby On Rails

๐Ÿš€ Power Up Your App with Push Notifications in Ruby on Rails! ๐Ÿ“ฒ

Push notifications are an excellent way to engage users by sending timely, relevant updates directly to their devices. In this blog, weโ€™ll dive into the world of push notifications in Ruby on Rails. Whether itโ€™s a simple notification system or complex third-party integrations, weโ€™ve got you covered! Letโ€™s explore the various options and learn how to set up each with examples. ๐Ÿ’ก

12_Steps_for_Handling_Push_Notifications_in_Ruby_on_Rails


๐Ÿ› ๏ธ Types of Push Notifications in Rails

  1. In-App Notifications ๐Ÿ“ฉ
  2. Web Push Notifications ๐ŸŒ
  3. Mobile Push Notifications ๐Ÿ“ฑ
  4. Email as Push Notifications โœ‰๏ธ
  5. Using Third-Party Services ๐Ÿ› ๏ธ

1. In-App Notifications ๐Ÿ“ฉ

In-app notifications appear within your application. Rails has several ways to implement these, including creating your own notification system or using gems like Notification or Noticed.

Setup Example with Noticed Gem

  1. Add the gem:

    gem 'noticed'
    
  2. Generate a Notification Model:

    rails generate noticed:model NewMessageNotification
    
  3. Define Notification Content:

    Edit app/notifications/new_message_notification.rb to customize the message:

    class NewMessageNotification < Noticed::Base
      deliver_by :database
         
      def message
        "You have a new message from #{params[:sender_name]}!"
      end
    end
    
  4. Trigger Notification:

    Use the notification within your controller:

    NewMessageNotification.with(sender_name: @user.name).deliver_later(recipient)
    
  5. Display Notification in View:

    <% current_user.notifications.each do |notification| %>
      <p><%= notification.message %></p>
    <% end %>
    

๐Ÿ’ก In-app notifications are perfect for alerting users of updates or activities while theyโ€™re actively using the app.


2. Web Push Notifications ๐ŸŒ

Web push notifications reach users even when theyโ€™re not actively browsing your app. To implement this in Rails, you can use the webpush gem to send messages directly to the browser.

Setup Example with webpush Gem

  1. Install the gem:

    gem 'webpush'
    
  2. Generate VAPID Keys:

    Use VAPID keys to authenticate your server with web browsers.

    require 'webpush'
    vapid_key = Webpush.generate_key
    
  3. Store and Use VAPID Keys:

    Save these keys in your credentials file for security.

  4. Send Push Notification:

    Webpush.payload_send(
      message: "Hello from Rails!",
      endpoint: subscription[:endpoint],
      p256dh: subscription[:keys][:p256dh],
      auth: subscription[:keys][:auth],
      vapid: {
        subject: "mailto:you@example.com",
        public_key: ENV['VAPID_PUBLIC_KEY'],
        private_key: ENV['VAPID_PRIVATE_KEY']
      }
    )
    

๐ŸŒ Web push notifications are great for re-engaging users after theyโ€™ve left your app.


3. Mobile Push Notifications ๐Ÿ“ฑ

For mobile apps, push notifications can be sent to iOS and Android devices using services like Firebase Cloud Messaging (FCM) for Android and Apple Push Notification Service (APNS) for iOS.

Setup Example with FCM (Firebase Cloud Messaging)

  1. Create a Firebase Project:

    Register your app in Firebase Console and get the FCM server key.

  2. Send Notification Using fcm Gem:

    gem 'fcm'
    
  3. Initialize and Send Notification:

    fcm = FCM.new("YOUR_SERVER_KEY")
    registration_ids = ["device_token_1", "device_token_2"]
    
    options = { notification: { title: "Hello!", body: "New message received." } }
    response = fcm.send(registration_ids, options)
    

๐Ÿ“ฑ Mobile push notifications keep users engaged on the go!


4. Email as Push Notifications โœ‰๏ธ

Emails work as an indirect push notification method. For Rails, Action Mailer provides an easy way to send emails with minimal setup.

Setup Example Using Action Mailer

  1. Generate Mailer:

    rails generate mailer NotificationMailer
    
  2. Define Mailer Content:

    class NotificationMailer < ApplicationMailer
      def new_message_email(user)
        @user = user
        mail(to: @user.email, subject: "You have a new message!")
      end
    end
    
  3. Trigger Email Notification:

    NotificationMailer.new_message_email(@user).deliver_later
    

๐Ÿ“ง Email notifications are ideal for transactional updates like password resets or order confirmations.


5. Using Third-Party Services ๐Ÿ› ๏ธ

For more advanced needs, third-party push notification services like OneSignal or Pusher provide robust features for managing notifications, targeting specific audiences, and gaining insights.

Setup Example with OneSignal

  1. Register for OneSignal:

    Sign up on OneSignal and create a new application.

  2. Install the OneSignal SDK:

    Use the provided instructions to set up OneSignal with your Rails app.

  3. Send Notification:

    Once integrated, you can send notifications via their API:

    require 'net/http'
    uri = URI("https://onesignal.com/api/v1/notifications")
    
    response = Net::HTTP.post(
      uri,
      {
        app_id: "YOUR_APP_ID",
        headings: { en: "New Update!" },
        contents: { en: "Check out the latest features!" },
        included_segments: ["Subscribed Users"]
      }.to_json,
      "Content-Type" => "application/json",
      "Authorization" => "Basic YOUR_REST_API_KEY"
    )
    

๐Ÿ’ฅ Third-party services are perfect for larger apps requiring in-depth analytics and segmented messaging.


๐Ÿ”ฅ Wrapping Up

Push notifications in Ruby on Rails can range from in-app alerts to sophisticated, multi-platform notifications. Each approach has its unique advantages:

  • In-App Notifications for real-time updates
  • Web Push for re-engagement
  • Mobile Push for reaching users on their phones
  • Email Notifications for important transactional messages
  • Third-Party Services for advanced customization and analytics

Adding push notifications takes your appโ€™s engagement to the next level, keeping users informed and connected. Give it a try, and start sending updates your users wonโ€™t want to miss! ๐ŸŽ‰

© Lakhveer Singh Rajput - Blogs. All Rights Reserved.