Class: Parse::Push

Inherits:
Object
  • Object
show all
Includes:
Client::Connectable
Defined in:
lib/parse/model/push.rb

Overview

This class represents the API to send push notification to devices that are available in the Installation table. Push notifications are implemented through the ‘Parse::Push` class. To send push notifications through the REST API, you must enable `REST push enabled?` option in the `Push Notification Settings` section of the `Settings` page in your Parse application. Push notifications targeting uses the Installation Parse class to determine which devices receive the notification. You can provide any query constraint, similar to using `Parse::Query`, in order to target the specific set of devices you want given the columns you have configured in your `Installation` class. The `Parse::Push` class supports many other options not listed here.

Examples:

Traditional API

# simple channel push (targeted, sends without opt-in)
push = Parse::Push.new
push.channels = ["addicted2salsa"]
push.send "You are subscribed to Addicted2Salsa!"

# advanced targeting
push = Parse::Push.new({..where query constraints..})
push.where :device_type.in => ['ios','android'], :location.near => some_geopoint
push.alert = "Hello World!"
push.sound = "soundfile.caf"
push.data = { uri: "app://deep_link_path" }
push.send

# broadcast to every Installation (requires explicit opt-in)
Parse::Push.new.broadcast!.send("Hello World!")
# or set process-wide: Parse::Push.allow_broadcast = true

Builder Pattern API (Fluent Interface)

# Simple channel push with builder pattern
Parse::Push.new
  .to_channel("news")
  .with_alert("Breaking news!")
  .send!

# Rich push with scheduling
Parse::Push.new
  .to_channels("sports", "updates")
  .with_title("Game Alert")
  .with_body("Your team is playing now!")
  .with_badge(1)
  .with_sound("alert.caf")
  .with_data(game_id: "12345")
  .schedule(1.hour.from_now)
  .expires_in(3600)
  .send!

# Using class method shortcut
Parse::Push.to_channel("alerts")
  .with_alert("Important update")
  .send!

# Using query block for advanced targeting
Parse::Push.new
  .to_query { |q| q.where(:device_type => "ios", :app_version.gte => "2.0") }
  .with_alert("iOS 2.0+ users only")
  .send!

Defined Under Namespace

Classes: AudienceNotFound, BroadcastNotAllowed

Constant Summary collapse

SUPPORTED_PUSH_DEVICE_TYPES =

Device types that support push notifications. These are the device types that Parse Server has push adapters for.

%w[ios android osx tvos watchos web expo].freeze
UNSUPPORTED_PUSH_DEVICE_TYPES =

Device types that are known but may not have push support configured. These will generate warnings when targeted.

%w[win other unknown unsupported].freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Client::Connectable

#client

Constructor Details

#initialize(constraints = {}) ⇒ Push

Initialize a new push notification request.

Parameters:

  • constraints (Hash) (defaults to: {})

    a set of query constraints



248
249
250
# File 'lib/parse/model/push.rb', line 248

def initialize(constraints = {})
  self.where constraints
end

Class Attribute Details

.allow_broadcastObject

Returns the value of attribute allow_broadcast.



99
100
101
# File 'lib/parse/model/push.rb', line 99

def allow_broadcast
  @allow_broadcast
end

Instance Attribute Details

#alertString Also known as: message

Returns:



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#badgeInteger

Returns:

  • (Integer)


148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#categoryString

Returns the notification category for action buttons (iOS).

Returns:

  • (String)

    the notification category for action buttons (iOS).



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#channelsArray

Returns an array of strings for subscribed channels.

Returns:

  • (Array)

    an array of strings for subscribed channels.



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#content_availableBoolean

Returns whether this is a silent push (iOS content-available).

Returns:

  • (Boolean)

    whether this is a silent push (iOS content-available).



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#dataHash

Returns specific payload data.

Returns:

  • (Hash)

    specific payload data.



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#expiration_intervalInteger

Returns:

  • (Integer)


148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#expiration_timeParse::Date

Returns:



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#image_urlString

Returns URL for an image attachment (requires mutable-content).

Returns:

  • (String)

    URL for an image attachment (requires mutable-content).



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#localized_alertsHash

Returns language-specific alert messages (e.g., => “Hello”, “fr” => “Bonjour”).

Returns:

  • (Hash)

    language-specific alert messages (e.g., => “Hello”, “fr” => “Bonjour”)



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#localized_titlesHash

Returns language-specific titles (e.g., => “Welcome”, “fr” => “Bienvenue”).

Returns:

  • (Hash)

    language-specific titles (e.g., => “Welcome”, “fr” => “Bienvenue”)



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#mutable_contentBoolean

Returns whether this notification can be modified by a service extension (iOS).

Returns:

  • (Boolean)

    whether this notification can be modified by a service extension (iOS).



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#push_timeParse::Date

Returns:



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#queryObject

Sending a push notification is done by performing a query against the Installation collection with a Parse::Query. This query contains the constraints that will be sent to Parse with the push payload.

@return [Parse::Query] the query containing Installation constraints.


# File 'lib/parse/model/push.rb', line 112

#soundString

Returns the name of the sound file.

Returns:

  • (String)

    the name of the sound file



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

#titleString

Returns:



148
# File 'lib/parse/model/push.rb', line 148

attr_writer :query

Class Method Details

.channelsArray<String>

List all available channels from the Installation collection. This is a convenience method that delegates to Installation.all_channels.

Examples:

available_channels = Parse::Push.channels
# => ["news", "sports", "weather"]

Returns:



188
189
190
# File 'lib/parse/model/push.rb', line 188

def self.channels
  Parse::Installation.all_channels
end

.send(payload) ⇒ Object

Send a push notification using a push notification hash

Parameters:

  • payload (Hash)

    a push notification hash payload



160
161
162
# File 'lib/parse/model/push.rb', line 160

def self.send(payload)
  client.push payload.as_json
end

.to_channel(channel) ⇒ Parse::Push

Create a new Push targeting a specific channel.

Examples:

Parse::Push.to_channel("news").with_alert("Hello!").send!

Parameters:

  • channel (String)

    the channel name to target

Returns:



169
170
171
# File 'lib/parse/model/push.rb', line 169

def self.to_channel(channel)
  new.to_channel(channel)
end

.to_channels(*channels) ⇒ Parse::Push

Create a new Push targeting multiple channels.

Examples:

Parse::Push.to_channels("news", "sports").with_alert("Update!").send!

Parameters:

  • channels (Array<String>)

    the channel names to target

Returns:



178
179
180
# File 'lib/parse/model/push.rb', line 178

def self.to_channels(*channels)
  new.to_channels(*channels)
end

.to_installation(installation) ⇒ Parse::Push

Create a new Push targeting a specific installation.

Examples:

Parse::Push.to_installation(device).with_alert("Hello!").send!

Parameters:

Returns:



224
225
226
# File 'lib/parse/model/push.rb', line 224

def self.to_installation(installation)
  new.to_installation(installation)
end

.to_installation_id(installation_id) ⇒ Parse::Push

Create a new Push targeting an installation by its objectId.

Examples:

Parse::Push.to_installation_id("abc123").with_alert("Hello!").send!

Parameters:

  • installation_id (String)

    the objectId of the installation to target

Returns:



233
234
235
# File 'lib/parse/model/push.rb', line 233

def self.to_installation_id(installation_id)
  new.to_installation_id(installation_id)
end

.to_installations(*installations) ⇒ Parse::Push

Create a new Push targeting multiple installations.

Examples:

Parse::Push.to_installations(device1, device2).with_alert("Hello!").send!

Parameters:

Returns:



242
243
244
# File 'lib/parse/model/push.rb', line 242

def self.to_installations(*installations)
  new.to_installations(*installations)
end

.to_user(user) ⇒ Parse::Push

Create a new Push targeting a specific user.

Examples:

Parse::Push.to_user(current_user).with_alert("Hello!").send!

Parameters:

Returns:



197
198
199
# File 'lib/parse/model/push.rb', line 197

def self.to_user(user)
  new.to_user(user)
end

.to_user_id(user_id) ⇒ Parse::Push

Create a new Push targeting a user by their objectId.

Examples:

Parse::Push.to_user_id("abc123").with_alert("Hello!").send!

Parameters:

  • user_id (String)

    the objectId of the user to target

Returns:



206
207
208
# File 'lib/parse/model/push.rb', line 206

def self.to_user_id(user_id)
  new.to_user_id(user_id)
end

.to_users(*users) ⇒ Parse::Push

Create a new Push targeting multiple users.

Examples:

Parse::Push.to_users(user1, user2).with_alert("Group message!").send!

Parameters:

Returns:



215
216
217
# File 'lib/parse/model/push.rb', line 215

def self.to_users(*users)
  new.to_users(*users)
end

Instance Method Details

#as_json(*args) ⇒ Hash

Returns a JSON encoded hash.

Returns:

  • (Hash)

    a JSON encoded hash.



297
298
299
# File 'lib/parse/model/push.rb', line 297

def as_json(*args)
  payload.as_json
end

#broadcast!self

Opt this specific push in to broadcasting to every Installation. Use when you legitimately want a global push and have not set the process-wide allow_broadcast. The explicit call site is the audit trail.

Examples:

Parse::Push.new.broadcast!.with_alert("Maintenance window").send!

Returns:

  • (self)

    for chaining



381
382
383
384
# File 'lib/parse/model/push.rb', line 381

def broadcast!
  @broadcast_allowed = true
  self
end

#broadcast_allowed?Boolean

Returns true when broadcasting is allowed for this push, either via the class-level allow_broadcast flag or the per-instance #broadcast! opt-in.

Returns:

  • (Boolean)

    true when broadcasting is allowed for this push, either via the class-level allow_broadcast flag or the per-instance #broadcast! opt-in.



389
390
391
# File 'lib/parse/model/push.rb', line 389

def broadcast_allowed?
  @broadcast_allowed == true || self.class.allow_broadcast == true
end

#clear_badgeself

Clear the badge (set to 0).

Examples:

push.clear_badge.silent!.send!  # Clear badge silently

Returns:

  • (self)

    returns self for method chaining



692
693
694
695
# File 'lib/parse/model/push.rb', line 692

def clear_badge
  self.badge = 0
  self
end

#content_available?Boolean

Check if this push has content-available set (silent push).

Returns:

  • (Boolean)

    true if content-available is enabled



278
279
280
# File 'lib/parse/model/push.rb', line 278

def content_available?
  @content_available == true
end

#expires_at(time) ⇒ self

Set the expiration time for this push notification. The push will not be delivered after this time.

Examples:

push.expires_at(2.hours.from_now).send!

Parameters:

Returns:

  • (self)

    returns self for method chaining



525
526
527
528
# File 'lib/parse/model/push.rb', line 525

def expires_at(time)
  self.expiration_time = time
  self
end

#expires_in(seconds) ⇒ self

Set the expiration interval for this push notification. The push will expire after this many seconds from now.

Examples:

push.expires_in(3600).send!  # Expires in 1 hour
push.expires_in(86400).send! # Expires in 24 hours

Parameters:

  • seconds (Integer)

    number of seconds until expiration

Returns:

  • (self)

    returns self for method chaining



537
538
539
540
# File 'lib/parse/model/push.rb', line 537

def expires_in(seconds)
  self.expiration_interval = seconds.to_i
  self
end

#increment_badge(amount = 1) ⇒ self

Increment the badge count instead of setting an absolute value. This is useful when you want to add to the existing badge rather than replace it.

Examples:

push.increment_badge.with_alert("New message!").send!     # +1
push.increment_badge(5).with_alert("5 new items!").send!  # +5

Parameters:

  • amount (Integer) (defaults to: 1)

    the amount to increment by (default: 1)

Returns:

  • (self)

    returns self for method chaining



679
680
681
682
683
684
685
686
# File 'lib/parse/model/push.rb', line 679

def increment_badge(amount = 1)
  if amount == 1
    self.badge = "Increment"
  else
    self.badge = { "__op" => "Increment", "amount" => amount.to_i }
  end
  self
end

#mutable!self

Enable mutable-content for iOS notification service extension. This allows the notification to be modified by a service extension before display.

Examples:

push.mutable!.with_data(encrypted_body: "...").send!

Returns:

  • (self)

    returns self for method chaining



587
588
589
590
# File 'lib/parse/model/push.rb', line 587

def mutable!
  @mutable_content = true
  self
end

#mutable_content?Boolean

Check if this push has mutable-content set (rich notifications).

Returns:

  • (Boolean)

    true if mutable-content is enabled



284
285
286
# File 'lib/parse/model/push.rb', line 284

def mutable_content?
  @mutable_content == true
end

#payloadHash

This method takes all the parameters of the instance and creates a proper hash structure, required by Parse, in order to process the push notification.

Returns:

  • (Hash)

    the prepared push payload to be used in the request.



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/parse/model/push.rb', line 309

def payload
  msg = {
    data: {
      alert: alert,
      badge: badge || "Increment",
    },
  }
  msg[:data][:sound] = sound if sound.present?
  msg[:data][:title] = title if title.present?
  msg[:data][:"content-available"] = 1 if content_available?
  msg[:data][:"mutable-content"] = 1 if mutable_content?
  msg[:data][:category] = @category if @category.present?
  msg[:data][:image] = @image_url if @image_url.present?

  # Add localized alerts (e.g., "alert-en", "alert-fr")
  if @localized_alerts.is_a?(Hash)
    @localized_alerts.each do |lang, text|
      msg[:data][:"alert-#{lang}"] = text
    end
  end

  # Add localized titles (e.g., "title-en", "title-fr")
  if @localized_titles.is_a?(Hash)
    @localized_titles.each do |lang, text|
      msg[:data][:"title-#{lang}"] = text
    end
  end

  msg[:data].merge! @data if @data.is_a?(Hash)

  if @expiration_time.present?
    msg[:expiration_time] = @expiration_time.respond_to?(:iso8601) ? @expiration_time.iso8601(3) : @expiration_time
  end
  if @push_time.present?
    msg[:push_time] = @push_time.respond_to?(:iso8601) ? @push_time.iso8601(3) : @push_time
  end

  if @expiration_interval.is_a?(Numeric)
    msg[:expiration_interval] = @expiration_interval.to_i
  end

  if query.where.present?
    q = @query.dup
    if @channels.is_a?(Array) && @channels.empty? == false
      q.where :channels.in => @channels
    end
    msg[:where] = q.compile_where unless q.where.empty?
  elsif @channels.is_a?(Array) && @channels.empty? == false
    msg[:channels] = @channels
  end
  msg
end

#schedule(time) ⇒ self

Schedule the push notification for a future time.

Examples:

push.schedule(1.hour.from_now).send!
push.schedule(Time.new(2025, 12, 25, 9, 0, 0)).send!

Parameters:

Returns:

  • (self)

    returns self for method chaining



514
515
516
517
# File 'lib/parse/model/push.rb', line 514

def schedule(time)
  self.push_time = time
  self
end

#send(message = nil) ⇒ Object

helper method to send a message

Parameters:

  • message (String) (defaults to: nil)

    the message to send

Raises:



367
368
369
370
371
372
# File 'lib/parse/model/push.rb', line 367

def send(message = nil)
  @alert = message if message.is_a?(String)
  @data = message if message.is_a?(Hash)
  assert_broadcast_allowed!
  client.push(payload.as_json)
end

#send!Parse::Response

Send the push notification, raising an error on failure. This is the bang version that raises Error if the push fails.

Examples:

push.with_alert("Hello!").send!

Returns:

Raises:



601
602
603
604
605
606
607
608
# File 'lib/parse/model/push.rb', line 601

def send!
  assert_broadcast_allowed!
  response = client.push(payload.as_json)
  if response.error?
    raise Parse::Error.new(response.code, response.error)
  end
  response
end

#silent!self

Mark this as a silent push notification (iOS content-available). Silent pushes wake the app in the background without displaying an alert.

Examples:

push.silent!.with_data(action: "sync").send!

Returns:

  • (self)

    returns self for method chaining

See Also:



548
549
550
551
# File 'lib/parse/model/push.rb', line 548

def silent!
  @content_available = true
  self
end

#to_audience(audience_name, cache: true) ⇒ self

Note:

The audience must exist in the _Audience collection

Target a saved audience by name. Audiences are pre-defined in the _Audience collection and can be reused. Uses caching by default for better performance.

Examples:

push.to_audience("VIP Users").with_alert("Exclusive offer!").send!

Parameters:

  • audience_name (String)

    the name of the saved audience

  • cache (Boolean) (defaults to: true)

    whether to use audience cache (default: true)

Returns:

  • (self)

    returns self for method chaining

Raises:

  • (AudienceNotFound)

    if no audience exists with the given name. Previously this method emitted a ‘warn` and returned `self`, which let the subsequent `send!` broadcast to every Installation. The raise makes typos and renames loud at the call site.



715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/parse/model/push.rb', line 715

def to_audience(audience_name, cache: true)
  # Use cached audience lookup for better performance
  audience = Parse::Audience.find_by_name(audience_name, cache: cache)

  if audience.nil?
    raise AudienceNotFound,
          "Audience '#{audience_name}' not found in _Audience collection"
  end

  if audience.query_constraint.present?
    # Merge the audience's query constraints into our query
    audience.query_constraint.each do |key, value|
      query.where(key.to_sym => value)
    end
  end
  self
end

#to_audience_id(audience_id) ⇒ self

Target a saved audience by its object ID.

Examples:

push.to_audience_id("abc123").with_alert("Hello!").send!

Parameters:

  • audience_id (String)

    the objectId of the saved audience

Returns:

  • (self)

    returns self for method chaining

Raises:



739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'lib/parse/model/push.rb', line 739

def to_audience_id(audience_id)
  audience = Parse::Audience.find(audience_id)
  if audience.nil?
    raise AudienceNotFound,
          "Audience id '#{audience_id}' not found in _Audience collection"
  end
  if audience.query_constraint.present?
    audience.query_constraint.each do |key, value|
      query.where(key.to_sym => value)
    end
  end
  self
end

#to_channel(channel) ⇒ self

Target a specific channel for this push notification.

Examples:

push.to_channel("news").with_alert("Update!").send!

Parameters:

  • channel (String)

    the channel name to target

Returns:

  • (self)

    returns self for method chaining



422
423
424
425
# File 'lib/parse/model/push.rb', line 422

def to_channel(channel)
  self.channels = [channel]
  self
end

#to_channels(*channels) ⇒ self

Target multiple channels for this push notification.

Examples:

push.to_channels("news", "sports").with_alert("Update!").send!

Parameters:

  • channels (Array<String>)

    the channel names to target

Returns:

  • (self)

    returns self for method chaining



432
433
434
435
# File 'lib/parse/model/push.rb', line 432

def to_channels(*channels)
  self.channels = channels.flatten
  self
end

#to_installation(installation) ⇒ self

Target a specific installation (or multiple installations) by object or objectId. This directly targets device installation(s).

When given a Parse::Installation object, this method validates:

  • The installation has a device_token (raises ArgumentError if missing)

  • The device_type is supported for push (warns if unsupported)

Examples:

With a Parse::Installation object

device = Parse::Installation.find("abc123")
Parse::Push.new.to_installation(device).with_alert("Hello!").send!

With an objectId

Parse::Push.new.to_installation("abc123").with_alert("Hello!").send!

With an array of installations

Parse::Push.new.to_installation([device1, device2]).with_alert("Hello!").send!

Using class method shortcut

Parse::Push.to_installation(device).with_alert("Device notification").send!

Parameters:

  • installation (Parse::Installation, Hash, String, Array)

    the installation(s) to target. Can be:

    • A Parse::Installation object

    • A hash with objectId key

    • An objectId string

    • An array of any of the above (delegates to to_installations)

Returns:

  • (self)

    returns self for method chaining

Raises:

  • (ArgumentError)

    if installation object has no device_token



873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
# File 'lib/parse/model/push.rb', line 873

def to_installation(installation)
  # Delegate to to_installations if given an array
  return to_installations(installation) if installation.is_a?(Array)

  object_id = case installation
    when Parse::Installation
      validate_installation_for_push!(installation)
      installation.id
    when Hash
      installation[:objectId] || installation["objectId"] || installation[:id] || installation["id"]
    when String
      installation
    else
      raise ArgumentError, "Expected Parse::Installation, Hash, String, or Array, got #{installation.class}"
    end

  query.where(objectId: object_id)
  self
end

#to_installation_id(installation_id) ⇒ self

Target a specific installation by its objectId. This is a convenience method equivalent to to_installation with a string ID.

Examples:

Parse::Push.new.to_installation_id("abc123").with_alert("Hello!").send!

Using class method shortcut

Parse::Push.to_installation_id("abc123").with_alert("Device notification").send!

Parameters:

  • installation_id (String)

    the objectId of the installation to target

Returns:

  • (self)

    returns self for method chaining



903
904
905
906
# File 'lib/parse/model/push.rb', line 903

def to_installation_id(installation_id)
  query.where(objectId: installation_id)
  self
end

#to_installations(*installations) ⇒ self

Target multiple installations. This queries the Installation collection for devices matching any of the given installation objectIds.

When given Parse::Installation objects, this method validates each:

  • The installation has a device_token (raises ArgumentError if missing)

  • The device_type is supported for push (warns if unsupported)

Examples:

Parse::Push.new.to_installations(device1, device2, device3).with_alert("Group notification!").send!

With objectIds

Parse::Push.new.to_installations("id1", "id2", "id3").with_alert("Hello devices!").send!

Parameters:

Returns:

  • (self)

    returns self for method chaining

Raises:

  • (ArgumentError)

    if any installation object has no device_token



924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
# File 'lib/parse/model/push.rb', line 924

def to_installations(*installations)
  object_ids = installations.flatten.map do |installation|
    case installation
    when Parse::Installation
      validate_installation_for_push!(installation)
      installation.id
    when Hash
      installation[:objectId] || installation["objectId"] || installation[:id] || installation["id"]
    when String
      installation
    else
      raise ArgumentError, "Expected Parse::Installation, Hash, or String, got #{installation.class}"
    end
  end

  query.where(:objectId.in => object_ids)
  self
end

#to_json(*args) ⇒ String

Returns a JSON encoded string.

Returns:

  • (String)

    a JSON encoded string.



302
303
304
# File 'lib/parse/model/push.rb', line 302

def to_json(*args)
  as_json.to_json
end

#to_query {|Parse::Query| ... } ⇒ self

Configure the push query using a block. The block receives the query object for adding constraints.

Examples:

push.to_query { |q| q.where(:device_type => "ios") }.send!

Yields:

Returns:

  • (self)

    returns self for method chaining



443
444
445
446
# File 'lib/parse/model/push.rb', line 443

def to_query
  yield query if block_given?
  self
end

#to_user(user) ⇒ self

Target installations belonging to a specific user (or multiple users). This queries the Installation collection for devices where the user pointer matches the given user(s).

Examples:

With a Parse::User object

user = Parse::User.find("abc123")
Parse::Push.new.to_user(user).with_alert("Hello!").send!

With a user objectId

Parse::Push.new.to_user("abc123").with_alert("Hello!").send!

With an array of users

Parse::Push.new.to_user([user1, user2]).with_alert("Hello!").send!

Using class method shortcut

Parse::Push.to_user(current_user).with_alert("Welcome back!").send!

Parameters:

  • user (Parse::User, Hash, String, Array)

    the user(s) to target. Can be:

    • A Parse::User object

    • A pointer hash (e.g., { “__type” => “Pointer”, “className” => “_User”, “objectId” => “abc123” })

    • A user objectId string (will be converted to a pointer)

    • An array of any of the above (delegates to to_users)

Returns:

  • (self)

    returns self for method chaining



779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
# File 'lib/parse/model/push.rb', line 779

def to_user(user)
  # Delegate to to_users if given an array
  return to_users(user) if user.is_a?(Array)

  pointer = case user
    when Parse::User
      user.pointer
    when Hash
      user
    when String
      Parse::Pointer.new(Parse::Model::CLASS_USER, user).to_h
    else
      raise ArgumentError, "Expected Parse::User, Hash, String, or Array, got #{user.class}"
    end

  query.where(user: pointer)
  self
end

#to_user_id(user_id) ⇒ self

Target installations belonging to a user by their objectId. This is a convenience method equivalent to to_user with a string ID.

Examples:

Parse::Push.new.to_user_id("abc123").with_alert("Hello!").send!

Using class method shortcut

Parse::Push.to_user_id("abc123").with_alert("You have a message").send!

Parameters:

  • user_id (String)

    the objectId of the user to target

Returns:

  • (self)

    returns self for method chaining



808
809
810
811
812
# File 'lib/parse/model/push.rb', line 808

def to_user_id(user_id)
  pointer = Parse::Pointer.new(Parse::Model::CLASS_USER, user_id).to_h
  query.where(user: pointer)
  self
end

#to_users(*users) ⇒ self

Target installations belonging to multiple users. This queries the Installation collection for devices where the user pointer matches any of the given users.

Examples:

Parse::Push.new.to_users(user1, user2, user3).with_alert("Group message!").send!

With user IDs

Parse::Push.new.to_users("id1", "id2", "id3").with_alert("Hello everyone!").send!

Parameters:

Returns:

  • (self)

    returns self for method chaining



825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'lib/parse/model/push.rb', line 825

def to_users(*users)
  pointers = users.flatten.map do |user|
    case user
    when Parse::User
      user.pointer
    when Hash
      user
    when String
      Parse::Pointer.new(Parse::Model::CLASS_USER, user).to_h
    else
      raise ArgumentError, "Expected Parse::User, Hash, or String, got #{user.class}"
    end
  end

  query.where(:user.in => pointers)
  self
end

#where(constraints = nil) ⇒ Hash, Parse::Query

Apply a set of constraints.

Parameters:

  • constraints (Hash) (defaults to: nil)

    the set of Query cosntraints

Returns:

  • (Hash)

    if no constraints were passed, returns a compiled query.

  • (Parse::Query)

    if constraints were passed, returns the chainable query.



266
267
268
269
270
# File 'lib/parse/model/push.rb', line 266

def where(constraints = nil)
  return query.compile_where unless constraints.is_a?(Hash)
  query.where constraints
  query
end

#where=(where_clauses) ⇒ Parse::Query

Set a hash of conditions for this push query.

Returns:



258
259
260
# File 'lib/parse/model/push.rb', line 258

def where=(where_clauses)
  query.where where_clauses
end

#with_alert(message) ⇒ self

Set the alert message for this push notification.

Examples:

push.with_alert("Hello World!").send!

Parameters:

  • message (String)

    the alert message

Returns:

  • (self)

    returns self for method chaining



453
454
455
456
# File 'lib/parse/model/push.rb', line 453

def with_alert(message)
  self.alert = message
  self
end

#with_badge(count) ⇒ self

Set the badge number for this push notification.

Examples:

push.with_badge(5).send!  # Set to 5
push.with_badge(0).send!  # Clear badge

Parameters:

  • count (Integer, String)

    the badge count, or “Increment” to increment

Returns:

  • (self)

    returns self for method chaining



482
483
484
485
# File 'lib/parse/model/push.rb', line 482

def with_badge(count)
  self.badge = count
  self
end

#with_body(body) ⇒ self

Alias for #with_alert - sets the body text of the notification.

Parameters:

  • body (String)

    the body/alert message

Returns:

  • (self)

    returns self for method chaining

See Also:



462
463
464
# File 'lib/parse/model/push.rb', line 462

def with_body(body)
  with_alert(body)
end

#with_category(category_name) ⇒ self

Set the notification category for action buttons (iOS). Categories must be registered in the app’s notification settings.

Examples:

push.with_category("MESSAGE_ACTIONS").with_alert("New message").send!

Parameters:

  • category_name (String)

    the notification category identifier

Returns:

  • (self)

    returns self for method chaining

See Also:



577
578
579
580
# File 'lib/parse/model/push.rb', line 577

def with_category(category_name)
  @category = category_name
  self
end

#with_data(hash) ⇒ self

Set custom data payload for this push notification.

Examples:

push.with_data(article_id: "123", action: "open").send!

Parameters:

  • hash (Hash)

    custom key-value pairs to include in the payload

Returns:

  • (self)

    returns self for method chaining



502
503
504
505
506
# File 'lib/parse/model/push.rb', line 502

def with_data(hash)
  @data ||= {}
  @data.merge!(hash.symbolize_keys)
  self
end

#with_image(url) ⇒ self

Add an image attachment to the push notification. This automatically enables mutable-content for iOS service extension processing.

Examples:

push.with_image("https://example.com/image.jpg").with_alert("Check this out!").send!

Parameters:

  • url (String)

    the URL of the image to attach

Returns:

  • (self)

    returns self for method chaining

See Also:



564
565
566
567
568
# File 'lib/parse/model/push.rb', line 564

def with_image(url)
  @image_url = url
  @mutable_content = true
  self
end

#with_localized_alert(lang, message) ⇒ self

Add a localized alert message for a specific language. Parse Server will automatically send the appropriate message based on device locale.

Examples:

push.with_localized_alert(:en, "Hello!")
    .with_localized_alert(:fr, "Bonjour!")
    .with_localized_alert(:es, "Hola!")
    .send!

Parameters:

  • lang (String, Symbol)

    the language code (e.g., :en, :fr, :es, :de)

  • message (String)

    the alert message in that language

Returns:

  • (self)

    returns self for method chaining



624
625
626
627
628
# File 'lib/parse/model/push.rb', line 624

def with_localized_alert(lang, message)
  @localized_alerts ||= {}
  @localized_alerts[lang.to_s] = message
  self
end

#with_localized_alerts(translations) ⇒ self

Set multiple localized alerts at once.

Examples:

push.with_localized_alerts(en: "Hello!", fr: "Bonjour!", es: "Hola!").send!

Parameters:

  • translations (Hash)

    a hash of language codes to messages

Returns:

  • (self)

    returns self for method chaining



651
652
653
654
655
# File 'lib/parse/model/push.rb', line 651

def with_localized_alerts(translations)
  @localized_alerts ||= {}
  translations.each { |lang, msg| @localized_alerts[lang.to_s] = msg }
  self
end

#with_localized_title(lang, title) ⇒ self

Add a localized title for a specific language. Parse Server will automatically send the appropriate title based on device locale.

Examples:

push.with_localized_title(:en, "Welcome")
    .with_localized_title(:fr, "Bienvenue")
    .with_alert("Default message")
    .send!

Parameters:

  • lang (String, Symbol)

    the language code (e.g., :en, :fr, :es, :de)

  • title (String)

    the title in that language

Returns:

  • (self)

    returns self for method chaining



640
641
642
643
644
# File 'lib/parse/model/push.rb', line 640

def with_localized_title(lang, title)
  @localized_titles ||= {}
  @localized_titles[lang.to_s] = title
  self
end

#with_localized_titles(translations) ⇒ self

Set multiple localized titles at once.

Examples:

push.with_localized_titles(en: "Welcome", fr: "Bienvenue").send!

Parameters:

  • translations (Hash)

    a hash of language codes to titles

Returns:

  • (self)

    returns self for method chaining



662
663
664
665
666
# File 'lib/parse/model/push.rb', line 662

def with_localized_titles(translations)
  @localized_titles ||= {}
  translations.each { |lang, title| @localized_titles[lang.to_s] = title }
  self
end

#with_sound(sound_name) ⇒ self

Set the sound file for this push notification.

Examples:

push.with_sound("notification.caf").send!

Parameters:

  • sound_name (String)

    the name of the sound file

Returns:

  • (self)

    returns self for method chaining



492
493
494
495
# File 'lib/parse/model/push.rb', line 492

def with_sound(sound_name)
  self.sound = sound_name
  self
end

#with_title(title) ⇒ self

Set the title for this push notification (appears above the alert).

Examples:

push.with_title("News").with_body("Article published").send!

Parameters:

  • title (String)

    the notification title

Returns:

  • (self)

    returns self for method chaining



471
472
473
474
# File 'lib/parse/model/push.rb', line 471

def with_title(title)
  self.title = title
  self
end