Class: Rapns::Notification

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/rapns/notification.rb

Instance Method Summary collapse

Instance Method Details

#alertObject



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rapns/notification.rb', line 28

def alert
  string_or_json = read_attribute(:alert)

  if has_attribute?(:alert_is_json)
    if alert_is_json?
      ActiveSupport::JSON.decode(string_or_json)
    else
      string_or_json
    end
  else
    ActiveSupport::JSON.decode(string_or_json) rescue string_or_json
  end
end

#alert=(alert) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/rapns/notification.rb', line 18

def alert=(alert)
  if alert.is_a?(Hash)
    write_attribute(:alert, ActiveSupport::JSON.encode(alert))
    self.alert_is_json = true if has_attribute?(:alert_is_json)
  else
    write_attribute(:alert, alert)
    self.alert_is_json = false if has_attribute?(:alert_is_json)
  end
end

#as_jsonObject



51
52
53
54
55
56
57
58
59
# File 'lib/rapns/notification.rb', line 51

def as_json
  json = ActiveSupport::OrderedHash.new
  json['aps'] = ActiveSupport::OrderedHash.new
  json['aps']['alert'] = alert if alert
  json['aps']['badge'] = badge if badge
  json['aps']['sound'] = sound if sound
  attributes_for_device.each { |k, v| json[k.to_s] = v.to_s } if attributes_for_device
  json
end

#attributes_for_deviceObject



47
48
49
# File 'lib/rapns/notification.rb', line 47

def attributes_for_device
  ActiveSupport::JSON.decode(read_attribute(:attributes_for_device)) if read_attribute(:attributes_for_device)
end

#attributes_for_device=(attrs) ⇒ Object

Raises:

  • (ArgumentError)


42
43
44
45
# File 'lib/rapns/notification.rb', line 42

def attributes_for_device=(attrs)
  raise ArgumentError, "attributes_for_device must be a Hash" if !attrs.is_a?(Hash)
  write_attribute(:attributes_for_device, ActiveSupport::JSON.encode(attrs))
end

#device_token=(token) ⇒ Object



14
15
16
# File 'lib/rapns/notification.rb', line 14

def device_token=(token)
  write_attribute(:device_token, token.delete(" <>")) if !token.nil?
end

#payloadObject



61
62
63
# File 'lib/rapns/notification.rb', line 61

def payload
  as_json.to_json
end

#payload_sizeObject



65
66
67
# File 'lib/rapns/notification.rb', line 65

def payload_size
  payload.bytesize
end

#to_binary(options = {}) ⇒ Object



71
72
73
74
# File 'lib/rapns/notification.rb', line 71

def to_binary(options = {})
  id_for_pack = options[:for_validation] ? 0 : id
  [1, id_for_pack, expiry, 0, 32, device_token, 0, payload_size, payload].pack("cNNccH*cca*")
end