Sha256: 6751ecf3f97f20135ebb2e47aa495da343f375581529fe0367db352676397728

Contents?: true

Size: 1.09 KB

Versions: 5

Compression:

Stored size: 1.09 KB

Contents

require 'json'
require_relative 'no_payload_error'

module Grocer
  class Notification
    attr_accessor :identifier, :expiry, :device_token, :alert, :badge, :sound,
                  :custom

    def initialize(payload = {})
      @identifier = 0

      payload.each do |key, val|
        send("#{key}=", val)
      end
    end

    def to_bytes
      validate_payload
      payload = encoded_payload

      [1, identifier, expiry_epoch_time, device_token_length, sanitized_device_token, payload.length].pack('CNNnH64n') << payload
    end

    private

    def validate_payload
      fail NoPayloadError unless alert || badge
    end

    def encoded_payload
      JSON.dump(payload_hash)
    end

    def payload_hash
      aps_hash = { }
      aps_hash[:alert] = alert if alert
      aps_hash[:badge] = badge if badge
      aps_hash[:sound] = sound if sound

      { aps: aps_hash }.merge(custom || { })
    end

    def expiry_epoch_time
      expiry.to_i
    end

    def sanitized_device_token
      device_token.tr(' ', '') if device_token
    end

    def device_token_length
      32
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
grocer-0.0.10 lib/grocer/notification.rb
grocer-0.0.9 lib/grocer/notification.rb
grocer-0.0.8 lib/grocer/notification.rb
grocer-0.0.7 lib/grocer/notification.rb
grocer-0.0.6 lib/grocer/notification.rb