How to send push notifications from your Rails application

Original author: juretriglav
  • Transfer
One of the most popular ways to communicate a mobile application with a server is to send push notifications to the user. If you are already faced with the implementation of push notifications, then the discovery of America will not happen for you, however, newcomers to this topic have to tight - this is due to a huge confusion in the information (from the translator: there are really quite a lot of contradictory, and often completely useless information) . It was this confusion that led to the writing of this article for WellWithMe, where I will describe the development of the server side of push notifications.



Before I continue, I must warn you of plug-n-play services that provide push notifications if you want to pay them ( Parse , mobDB , Pushwoosh ,Urban Airship , etc.), but this is not the way of a warrior. Let's do it ourselves, from scratch (and for free) (in fact - not so from scratch, but no one will have to pay) .

If you want to make an apple pie from scratch, then first create the universe
Carl Sagan

Here are three components that play an important role in our push notification delivery system:
  • API method for receiving tokens of mobile devices
  • Worker - constantly connected to Apple / Google servers and monitors the queue in Redis
  • A code that, in fact, sends messages to the queue


First of all, you need to ask the user if he wants to receive push notifications (golden words) and if the user agrees, send device token (I don’t know how to translate, I think everyone will understand device token) . We will save them (device token) into a simple ActiveRecord model, which we will call Device
# Schema Information
# Table name: devices
#  id         :integer          not null, primary key
#  user_id    :integer
#  token      :string(255)
#  enabled    :boolean          default(TRUE)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  platform   :string(255)
class Device < ActiveRecord::Base
  attr_accessible :enabled, :token, :user, :platform
  belongs_to :user
  validates_uniqueness_of :token, :scope => :user_id
end


Device instances (writes to the database) must be created when the application calls the appropriate API method

resource :devices do
  post do
    @device = Device.create(user: current_user, token: params[:token], platform: params[:platform])
    present @device, with: WellWithMe::Entities::Device
  end
end


Using the Notification Model from Redis as a Queue

class NotificationSender
  @queue = :notifications
  def self.perform
    @list = Redis::List.new(Notification.key_name)
    while notification = @list.pop do
      notification_json = JSON.parse(notification)
      if notification_json['platform'] == 'iOS'
        note = Grocer::Notification.new(
          device_token: notification_json['token'],
          alert: notification_json['message'],
          sound: 'default',
          badge: 0
        )
        PUSHER.push(note)
      elsif notification_json['platform'] == 'Android'
        gcm = GCM.new(ENV['gcm_key'])
        registration_id = [notification_json['token']]
        options = {
          'data' => {
            'message' => notification_json['message']
          },
            'collapse_key' => 'updated_state'
        }
        response = gcm.send_notification(registration_id, options)
      end
    end
  end
end


NotificationSender reads tasks from the queue while constantly maintaining a connection to the servers, without trying to establish new connections to send each push notification, which Apple is actively preventing: Apple's note about connecting to push notification servers

This code runs every minute, checking the Redis notification queue and sending out push device notifications.

Great grocer jams for iOS and GCM for Android were used. Both jams work great and are very well documented. The only limitation is that you must create certificates for iOS and export them correctly - just follow the instructions from Apple.

You now have an easily expandable push notification system. Push notifications will help to increase the number of your users, but do not abuse them, otherwise the opposite effect will occur.
And the translator will write his crutch in much the same way, only throwing Redis and adding Windows Phone

Also popular now: