Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/apncore.rb

Constant Summary collapse

MAX_PAYLOAD_LEN =
256

Instance Method Summary collapse

Instance Method Details

#payload_lengthFixnum?

Invokes #to_payload and returns it's length

Returns:

  • (Fixnum, nil)

    length of object converted into JSON or nil.


32
33
34
35
# File 'lib/apncore.rb', line 32

def payload_length
  p = to_payload
  p ? p.length : nil
end

#to_payloadString?

Converts hash into JSON String. When payload is too long but can be chopped, tries to cut self.[:alert]. If payload still don't fit Apple's restrictions, returns nil

Returns:

  • (String, nil)

    the object converted into JSON or nil.


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/apncore.rb', line 12

def to_payload
  # Payload too long
  if (to_json.length > MAX_PAYLOAD_LEN)
    alert = self[:aps][:alert]
    self[:aps][:alert] = ''
    # can be chopped?
    if (to_json.length > MAX_PAYLOAD_LEN)
      return nil
    else # inefficient way, but payload may be full of unicode-escaped chars, so...
      self[:aps][:alert] = alert
      while (self.to_json.length > MAX_PAYLOAD_LEN)
        self[:aps][:alert].chop!
      end
    end
  end
  to_json
end