Module: Parse::Core::Actions

Included in:
Object
Defined in:
lib/parse/model/core/actions.rb

Overview

Defines some of the save, update and destroy operations for Parse objects.

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

TRANSACTION_CONTEXT_KEY =

Fiber-local context used to capture an object's state before its first mutation inside a transaction block. batch.add is intentionally too late for this: the public API documents mutating an object and adding it afterwards.

:__parse_transaction_context__
TRANSACTION_CONFLICT_CODE =

Parse Server error code for a transaction write conflict.

251
UNDEFINED_PROPERTY =

Distinguishes a property whose ivar did not exist from one explicitly set to nil. Rollback removes the former instead of defining it as nil.

Object.new.freeze
ROLLBACK_STATE_IVARS =

Non-property state that can change while building/submitting a batch and must be restored along with the @<field> property ivars.

%i[
  @changed_attributes
  @id
  @mutations_from_database
  @mutations_before_last_save
  @_acl_snapshot_before_change
  @_acl_pristine
  @_authorization_acl_state
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.capture_transaction_state(obj, context = , include_created: false) ⇒ Hash?

Capture an object's state once, before its first transaction mutation. Objects created inside the transaction defer capture until batch.add.

Parameters:

  • obj (Parse::Object) —

    object whose state should be captured.

  • context (Hash, nil) (defaults to: ) —

    transaction context; defaults to the current fiber.

  • include_created (Boolean) (defaults to: false) —

    capture a newly created object at add time.

Returns:

  • (Hash, nil) —

    the object's rollback state.



314
315
316
317
318
319
320
# File 'lib/parse/model/core/actions.rb', line 314

def self.capture_transaction_state(obj, context = Fiber[TRANSACTION_CONTEXT_KEY], include_created: false)
  return unless context && obj

  object_id = obj.object_id
  return if context[:created_objects].key?(object_id) && !include_created
  context[:snapshots][object_id] ||= snapshot_object_state(obj)
end

.dup_for_snapshot(value, seen = {}) ⇒ Object

Copy a property value deeply enough that later in-place mutation of the live value cannot reach the snapshot.

A plain dup is not sufficient for collection-backed properties: :array and association properties hold a Parse::CollectionProxy, and duplicating the proxy still shares the underlying @collection array, so widget.tags << "b" would mutate the snapshot too. The proxy's mutable backing arrays and nested values are duplicated as well. Parse objects nested inside values remain references: a pointer property should restore the same object, not manufacture a clone.

Parameters:

  • value (Object) —

    the live property value.

Returns:

  • (Object) —

    a copy safe to hold across the transaction.



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/parse/model/core/actions.rb', line 188

def self.dup_for_snapshot(value, seen = {})
  return value if value.nil? || value == true || value == false || value.is_a?(Symbol) || value.is_a?(Numeric)
  return value if defined?(Parse::Pointer) && value.is_a?(Parse::Pointer)

  object_id = value.object_id
  return seen[object_id] if seen.key?(object_id)

  case value
  when Array
    copy = value.dup
    copy.clear
    seen[object_id] = copy
    value.each { |item| copy << dup_for_snapshot(item, seen) }
    copy
  when Hash
    copy = value.dup
    copy.clear
    seen[object_id] = copy
    value.each do |key, item|
      copy[dup_for_snapshot(key, seen)] = dup_for_snapshot(item, seen)
    end
    copy
  when Parse::CollectionProxy
    copy = value.dup
    seen[object_id] = copy
    %i[@collection @additions @removals @changed_attributes].each do |ivar|
      next unless value.instance_variable_defined?(ivar)
      copy.instance_variable_set(ivar, dup_for_snapshot(value.instance_variable_get(ivar), seen))
    end
    %i[@mutations_from_database @mutations_before_last_save].each do |ivar|
      next unless value.instance_variable_defined?(ivar)
      tracker = value.instance_variable_get(ivar)
      copy.instance_variable_set(ivar, dup_mutation_tracker(tracker, copy, seen))
    end
    copy
  when Parse::ACL
    copy = Parse::ACL.new(dup_for_snapshot(value.as_json, seen), owner: value.delegate)
    seen[object_id] = copy
    copy
  else
    copy = begin
        value.dup
      rescue TypeError
        # Immutable values are safe to share with the snapshot.
        return value
      end
    seen[object_id] = copy
    copy
  end
end

.dup_mutation_tracker(tracker, owner, seen = {}) ⇒ Object?

Duplicate ActiveModel's mutation tracker without sharing its mutable forced/finalized change hashes. Forced trackers retain their owning Parse object (or copied collection proxy) so dirty reads keep working.

Parameters:

  • tracker (Object, nil) —

    ActiveModel mutation tracker.

  • owner (Object) —

    object whose attributes the copy should read.

  • seen (Hash) (defaults to: {}) —

    identity map used by dup_for_snapshot.

Returns:

  • (Object, nil) —

    isolated tracker copy.



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/parse/model/core/actions.rb', line 247

def self.dup_mutation_tracker(tracker, owner, seen = {})
  return nil if tracker.nil?
  return tracker if defined?(ActiveModel::NullMutationTracker) && tracker.is_a?(ActiveModel::NullMutationTracker)
  return seen[tracker.object_id] if seen.key?(tracker.object_id)

  copy = tracker.dup
  seen[tracker.object_id] = copy
  if defined?(ActiveModel::ForcedMutationTracker) && tracker.is_a?(ActiveModel::ForcedMutationTracker)
    copy.instance_variable_set(:@attributes, owner)
  end
  %i[@forced_changes @finalized_changes].each do |ivar|
    next unless tracker.instance_variable_defined?(ivar)
    copy.instance_variable_set(ivar, dup_for_snapshot(tracker.instance_variable_get(ivar), seen))
  end
  copy
rescue TypeError
  tracker
end

.mark_transaction_object_created(obj)

This method returns an undefined value.

Record that an object was initialized inside the active transaction. Its first rollback snapshot is intentionally taken when it is added to the batch, after initialization, so a failed create stays usable as an initialized unsaved object.

Parameters:



300
301
302
303
304
305
# File 'lib/parse/model/core/actions.rb', line 300

def self.mark_transaction_object_created(obj)
  context = Fiber[TRANSACTION_CONTEXT_KEY]
  return unless context
  context[:created_objects][obj.object_id] = true
  context[:snapshots].delete(obj.object_id)
end

.restore_instance_variable(obj, ivar, value)

This method returns an undefined value.

Restore one instance variable while preserving whether it originally existed. Used for dirty/ACL bookkeeping outside the property schema.

Parameters:



349
350
351
352
353
354
355
# File 'lib/parse/model/core/actions.rb', line 349

def self.restore_instance_variable(obj, ivar, value)
  if value.equal?(UNDEFINED_PROPERTY)
    obj.remove_instance_variable(ivar) if obj.instance_variable_defined?(ivar)
  else
    obj.instance_variable_set(ivar, value)
  end
end

.restore_property_values(obj, snapshot)

This method returns an undefined value.

Restore the values captured by snapshot_property_values.

Writes ivars directly rather than going through the property setters, since the setters mark the object dirty and the caller restores the dirty state itself immediately afterwards.

Parameters:



331
332
333
334
335
336
337
338
339
340
# File 'lib/parse/model/core/actions.rb', line 331

def self.restore_property_values(obj, snapshot)
  return unless snapshot.is_a?(Hash)
  snapshot.each do |ivar, value|
    if value.equal?(UNDEFINED_PROPERTY)
      obj.remove_instance_variable(ivar) if obj.instance_variable_defined?(ivar)
    else
      obj.instance_variable_set(ivar, value)
    end
  end
end

.rollback_object_state(state)

This method returns an undefined value.

Roll a single tracked object back to the state captured when it was added to the transaction.

Parameters:

  • state (Hash) —

    one entry of the transaction's original_states.



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/parse/model/core/actions.rb', line 362

def self.rollback_object_state(state)
  obj = state[:object]
  return if obj.nil?
  restore_property_values(obj, state[:property_values])
  if state[:instance_variables]
    state[:instance_variables].each do |ivar, value|
      restore_instance_variable(obj, ivar, value)
    end
  else
    # Compatibility with rollback states produced before the complete
    # snapshot format was introduced.
    obj.instance_variable_set(:@changed_attributes, state[:changed_attributes])
    obj.instance_variable_set(:@id, state[:id])
    obj.instance_variable_set(:@mutations_from_database, state[:mutations_from_database])
    obj.instance_variable_set(:@mutations_before_last_save, state[:mutations_before_last_save])
  end
end

.snapshot_object_state(obj) ⇒ Hash

Capture all local state needed to restore an object after a failed transaction. This is separate from #attributes, which is a schema.

Parameters:

Returns:

  • (Hash) —

    rollback state.



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/parse/model/core/actions.rb', line 271

def self.snapshot_object_state(obj)
  seen = {}
  instance_variables = ROLLBACK_STATE_IVARS.each_with_object({}) do |ivar, snapshot|
    snapshot[ivar] = if obj.instance_variable_defined?(ivar)
        value = obj.instance_variable_get(ivar)
        if %i[@mutations_from_database @mutations_before_last_save].include?(ivar)
          dup_mutation_tracker(value, obj, seen)
        else
          dup_for_snapshot(value, seen)
        end
      else
        UNDEFINED_PROPERTY
      end
  end

  {
    object: obj,
    property_values: snapshot_property_values(obj),
    instance_variables: instance_variables,
  }
end

.snapshot_property_values(obj) ⇒ Hash

Capture the property values a transaction rollback must restore.

Property values live in @<field> instance variables (see Properties::ClassMethods#property), so those are what gets snapshotted. Object#attributes is deliberately NOT captured: it returns a SCHEMA map (field name to type symbol), not values, so restoring it never rolled anything back.

Restoring it was also actively harmful. @attributes is the ivar ActiveModel::Dirty keys its behavior on: mutations_from_database builds an AttributeMutationTracker over @attributes the moment that ivar is defined (and a ForcedMutationTracker otherwise), while forget_attribute_assignments calls map(&:forgetting_assignment) on it. Handing either one a schema Hash raised NoMethodError on a type symbol and on the [key, value] pair Hash#map yields. Both sites rescue and warn, so every rollback silently downgraded the object to broken change tracking instead of failing.

Parameters:

Returns:

  • (Hash) —

    field name to a snapshot of its value. Mutable values are duplicated so in-place mutation between snapshot and rollback cannot corrupt the saved copy.



160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/parse/model/core/actions.rb', line 160

def self.snapshot_property_values(obj)
  fields = obj.class.respond_to?(:fields) ? obj.class.fields.keys : []
  relations = obj.class.respond_to?(:relations) ? obj.class.relations.keys : []
  property_keys = (fields + relations).uniq
  seen = {}
  property_keys.each_with_object({}) do |key, snapshot|
    ivar = :"@#{key}"
    snapshot[ivar] = if obj.instance_variable_defined?(ivar)
        dup_for_snapshot(obj.instance_variable_get(ivar), seen)
      else
        UNDEFINED_PROPERTY
      end
  end
end

Instance Method Details

#_deleted? ⇒ Boolean

Returns true if this object has been fetched and found to be deleted from the server. Deleted objects cannot be saved.

Returns:

  • (Boolean) —

    true if the object is marked as deleted



1649
1650
1651
# File 'lib/parse/model/core/actions.rb', line 1649

def _deleted?
  @_deleted == true
end

#change_requests(force = false) ⇒ Array<Parse::Request>

Creates an array of all possible operations that need to be performed on this object. This includes all property and relational operation changes. Each request carries this class's client, so a batch sends it with the same credentials as a single #save.

This is the path batch saves (Array#save) and Object.transaction use, so it applies the same save-time rules as #save that do not depend on callbacks:

  • a new object resolves its Object.acl_policy owner ACL first, so batch-created records get the same ACL as single saves;
  • a new object sends its relation additions in the create body, since there is no objectId yet for a separate relation PUT;
  • a reference to an unsaved object raises RecordNotSaved instead of writing a pointer with a null objectId.

Parameters:

  • force (Boolean) (defaults to: false) —

    whether this object should be saved even if does not have pending changes.

Returns:

Raises:

  • (Parse::RecordNotSaved) —

    if a pointer, array or relation field references an object that has not been saved.



1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
# File 'lib/parse/model/core/actions.rb', line 1312

def change_requests(force = false)
  requests = []
  # get the URI path for this object.
  uri = self.uri_path
  creating = new?

  _resolve_default_acl if creating && respond_to?(:_resolve_default_acl, true)
  _assert_no_unsaved_references!

  if creating
    body = attribute_updates
    relation_additions = relation_changes? ? relation_change_operations.first : {}
    if attribute_changes? || relation_additions.present? || force
      body.merge!(relation_additions)
      # Forward a client-assigned objectId, as {#create} does.
      body[Parse::Model::OBJECT_ID] = @id if @id.present?
      r = Request.new(:post, uri, body: body)
      r.tag = object_id
      r.client = client
      requests << r
    end
    return requests
  end

  # generate the request to update the object (PUT)
  if attribute_changes? || force
    r = Request.new(:put, uri, body: attribute_updates)
    r.tag = object_id
    r.client = client
    requests << r
  end

  # if the object is not new, then we can also add all the relational changes
  # we need to perform.
  if @id.present? && relation_changes?
    relation_change_operations.each do |ops|
      next if ops.empty?
      r = Request.new(:put, uri, body: ops)
      r.tag = object_id
      r.client = client
      requests << r
    end
  end
  requests
end

#changes_applied! ⇒ Object

Clears changes information on all collections (array and relations) and all local attributes.



1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
# File 'lib/parse/model/core/actions.rb', line 1789

def changes_applied!
  # Settle the array and relation proxies that exist. Read the ivar
  # rather than the getter: the getter can autofetch a pointer or
  # build an empty proxy, and neither has changes to settle. A
  # relation proxy also drops its saved additions and removals here,
  # so a later save does not send them again.
  (fields(:array).keys + relations.keys).uniq.each do |key|
    ivar = :"@#{key}"
    next unless instance_variable_defined?(ivar)
    proxy = instance_variable_get(ivar)
    proxy.changes_applied! if proxy.respond_to?(:changes_applied!)
  end
  changes_applied
  # The saved ACL is the new baseline. Without this, the snapshot from
  # before the first edit survived the save, so `acl_was` kept
  # reporting the pre-save ACL: revoking a grant after saving it
  # compared equal to that stale snapshot, `acl_changed?` was false,
  # and the revocation was silently dropped while save returned true.
  @_acl_snapshot_before_change = nil
end

#changes_payload ⇒ Hash Also known as: update_payload

Returns a hash of the list of changes made to this instance.

Returns:

  • (Hash) —

    a hash of the list of changes made to this instance.



1697
1698
1699
1700
1701
1702
1703
1704
1705
# File 'lib/parse/model/core/actions.rb', line 1697

def changes_payload
  h = attribute_updates
  if relation_changes?
    r = relation_change_operations.select { |s| s.present? }.first
    h.merge!(r) if r.present?
  end
  #h.merge!(className: parse_class) unless h.empty?
  h.as_json
end

#create ⇒ Boolean

Save the object as a new record, running all callbacks.

Returns:

  • (Boolean) —

    true/false whether it was successful.



1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
# File 'lib/parse/model/core/actions.rb', line 1462

def create
  run_callbacks :create do
    # Checked after the before_save / before_create callbacks so a
    # callback that saves the referenced object first still works.
    next false unless _check_unsaved_references
    body = attribute_updates
    # Forward a client-assigned objectId when a `before_create` callback
    # set it (e.g. `parse_reference precompute: true`). attribute_updates
    # excludes BASE_KEYS, so @id must be merged explicitly. Parse Server
    # accepts an objectId in the create POST body and rejects duplicates
    # with a typed error rather than silently overwriting.
    body[Parse::Model::OBJECT_ID] = @id if @id.present?
    res = client.create_object(parse_class, body, session_token: _session_token)
    # Retain the response so wrappers (e.g. synchronize_create) can
    # inspect the Parse error code on failure (notably 137 DuplicateValue).
    @_last_response = res
    unless res.error?
      result = res.result
      @id = result[Parse::Model::OBJECT_ID] || @id
      # Store Parse::Date values, not the raw ISO strings. The :date
      # property reader converts a String on read and marks the field
      # dirty while doing so, which made a freshly created record
      # report unsaved changes (and send an empty PUT on the next
      # save) as soon as `updated_at` was read.
      @created_at = _server_date(result["createdAt"]) || @created_at
      #if the object is created, updatedAt == createdAt
      @updated_at = _server_date(result["updatedAt"] || result["createdAt"]) || @updated_at
      # Because beforeSave hooks can change the fields we are saving, any items that were
      # changed, are returned to us and we should apply those locally to be in sync.
      set_attributes!(result)
    end
    puts "Error creating #{self.parse_class}: #{res.error}" if res.error?
    res.success?
  end
end

#destroy(session: nil) ⇒ Boolean

Delete this record from the Parse collection. Only valid if this object has an id. This will run all the destroy callbacks.

After a successful destroy the object keeps its id, Object#destroyed? returns true and Object#persisted? returns false. Saving a destroyed object is refused: #save returns false and #save! raises RecordNotSaved, as in ActiveRecord.

Parameters:

  • session (String) (defaults to: nil) —

    a session token if you want to apply ACLs for a user in this operation.

Returns:

  • (Boolean) —

    whether the operation was successful.

Raises:

  • ArgumentError if a non-nil value is passed to session that doesn't provide a session token string.



1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
# File 'lib/parse/model/core/actions.rb', line 1663

def destroy(session: nil)
  @_session_token = _validate_session_token! session, :destroy
  return false if new?
  success = false
  run_callbacks :destroy do
    res = client.delete_object parse_class, id, session_token: _session_token
    success = res.success?
    if success
      # Keep the objectId so `dom_id`, `to_key` and Turbo Stream
      # removals still identify the record, and mark it destroyed so
      # `persisted?` is false and a later `save` refuses rather than
      # recreating it.
      @_destroyed = true
      changes_applied!
    elsif self.class.raise_on_save_failure
      raise Parse::RecordNotSaved.new(self), "Failed to create or save attributes. #{self.parse_class} was not saved."
    end
    # Your create action methods here
  end
  @_session_token = nil
  success
end

#destroy_request ⇒ Parse::Request

Returns a destroy_request for the current object.

Returns:



1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
# File 'lib/parse/model/core/actions.rb', line 1277

def destroy_request
  return nil unless @id.present?
  uri = self.uri_path
  r = Request.new(:delete, uri)
  r.tag = object_id
  # A batch sends this through the class's client (and its bound
  # session), as a single destroy does.
  r.client = client
  r
end

#op_add!(field, objects) ⇒ Boolean

Perform an atomic add operation to the array field.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

  • objects (Array) —

    the set of items to add to this field.

Returns:

  • (Boolean) —

    whether it was successful

See Also:



1172
1173
1174
# File 'lib/parse/model/core/actions.rb', line 1172

def op_add!(field, objects)
  operate_field! field, { __op: :Add, objects: objects }
end

#op_add_relation!(field, objects = []) ⇒ Boolean

Perform an atomic add operation on this relational field.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

  • objects (Array<Parse::Object>) (defaults to: []) —

    the set of objects to add to this relational field.

Returns:

  • (Boolean) —

    whether it was successful

See Also:



1222
1223
1224
1225
1226
1227
1228
1229
# File 'lib/parse/model/core/actions.rb', line 1222

def op_add_relation!(field, objects = [])
  objects = [objects] unless objects.is_a?(Array)
  return false if objects.empty?
  # The operation is keyed by the remote column, as a save sends it.
  remote_field = self.field_map[field.to_sym] || field
  relation_action = Parse::RelationAction.new(remote_field, polarity: true, objects: objects)
  operate_field! field, relation_action
end

#op_add_unique!(field, objects) ⇒ Boolean

Perform an atomic add unique operation to the array field. The objects will only be added if they don't already exists in the array for that particular field.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

  • objects (Array) —

    the set of items to add uniquely to this field.

Returns:

  • (Boolean) —

    whether it was successful

See Also:



1182
1183
1184
# File 'lib/parse/model/core/actions.rb', line 1182

def op_add_unique!(field, objects)
  operate_field! field, { __op: :AddUnique, objects: objects }
end

#op_destroy!(field) ⇒ Boolean

Perform an atomic delete operation on this field.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

Returns:

  • (Boolean) —

    whether it was successful

See Also:



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
# File 'lib/parse/model/core/actions.rb', line 1199

def op_destroy!(field)
  result = operate_field! field, { __op: :Delete }.freeze
  if result
    # Also update the local state to reflect the deletion
    field_sym = field.to_sym
    if self.class.fields[field_sym].present?
      set_attribute_method = "#{field}_set_attribute!"
      if respond_to?(set_attribute_method)
        send(set_attribute_method, nil, true) # Set to nil with dirty tracking
      else
        instance_variable_set(:"@#{field}", nil)
        send("#{field}_will_change!") if respond_to?("#{field}_will_change!")
      end
    end
  end
  result
end

#op_increment!(field, amount = 1) ⇒ Object

Atomically increment or decrement a specific field. This is the one place the local value is updated after the server applies the increment; the <field>_increment! helpers delegate here.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

  • amount (Numeric) (defaults to: 1) —

    the amount to increment. Use negative values to decrement. Integer amounts are sent as integers; any other Numeric is sent as a Float so fractional increments on Number columns are not truncated.

See Also:



1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
# File 'lib/parse/model/core/actions.rb', line 1253

def op_increment!(field, amount = 1)
  unless amount.is_a?(Numeric)
    raise ArgumentError, "Amount should be numeric"
  end
  amount = amount.is_a?(Integer) ? amount : amount.to_f
  result = operate_field! field, { __op: :Increment, amount: amount }.freeze
  if result
    # Also update the local state to reflect the increment.
    # operate_field! does not touch local state.
    field_sym = field.to_sym
    current_value = self[field_sym] || 0
    current_value = 0 unless current_value.is_a?(Numeric)
    new_value = current_value + amount
    set_attribute_method = "#{field}_set_attribute!"
    if respond_to?(set_attribute_method)
      send(set_attribute_method, new_value, true) # Set new value with dirty tracking
    else
      self[field_sym] = new_value
    end
  end
  result
end

#op_remove!(field, objects) ⇒ Boolean

Perform an atomic remove operation to the array field.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

  • objects (Array) —

    the set of items to remove to this field.

Returns:

  • (Boolean) —

    whether it was successful

See Also:



1191
1192
1193
# File 'lib/parse/model/core/actions.rb', line 1191

def op_remove!(field, objects)
  operate_field! field, { __op: :Remove, objects: objects }
end

#op_remove_relation!(field, objects = []) ⇒ Boolean

Perform an atomic remove operation on this relational field.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

  • objects (Array<Parse::Object>) (defaults to: []) —

    the set of objects to remove to this relational field.

Returns:

  • (Boolean) —

    whether it was successful

See Also:



1236
1237
1238
1239
1240
1241
1242
1243
# File 'lib/parse/model/core/actions.rb', line 1236

def op_remove_relation!(field, objects = [])
  objects = [objects] unless objects.is_a?(Array)
  return false if objects.empty?
  # The operation is keyed by the remote column, as a save sends it.
  remote_field = self.field_map[field.to_sym] || field
  relation_action = Parse::RelationAction.new(remote_field, polarity: false, objects: objects)
  operate_field! field, relation_action
end

#operate_field!(field, op_hash) ⇒ Boolean

Perform an atomic operation on this field. This operation is done on the Parse server which guarantees the atomicity of the operation. This is the low-level API on performing atomic operations on properties for classes. These methods do not update the current instance with any changes the server may have made to satisfy this operation.

Parameters:

  • field (String) —

    the name of the field in the Parse collection.

  • op_hash (Hash) —

    The operation hash. It may also be of type RelationAction.

Returns:

  • (Boolean) —

    whether the operation was successful.



1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
# File 'lib/parse/model/core/actions.rb', line 1129

def operate_field!(field, op_hash)
  # A reply from an earlier operation must never be read as this one's.
  @_last_operation_result = nil
  field = field.to_sym
  field = self.field_map[field] || field
  if op_hash.is_a?(Parse::RelationAction)
    op_hash = op_hash.as_json
  else
    op_hash = { field => op_hash }.as_json
  end

  # If the object hasn't been saved yet (no id), we can't make field operations
  # Return true to indicate the operation was "successful" locally
  return true if id.nil?

  response = client.update_object(parse_class, id, op_hash, session_token: _session_token)
  if response.error?
    puts "[#{parse_class}:#{field} Operation] #{response.error}"
  end
  # Keep the server's reply so a caller can adopt the field's new value
  # (Parse Server returns the whole array for Add/AddUnique/Remove).
  @_last_operation_result = response.success? && response.result.is_a?(Hash) ? response.result : nil
  response.success?
end

#prepare_save! ⇒ Boolean

Back-compat alias for Object#run_before_save_callbacks. The canonical name spells out exactly what runs (the before_save callbacks, before phase only) and is symmetric with run_after_save_callbacks / run_before_create_callbacks / run_after_create_callbacks. Retained so existing callers of prepare_save! keep working.

Returns:

  • (Boolean) —

    false if a before_save callback halted the chain, else true.



1692
1693
1694
# File 'lib/parse/model/core/actions.rb', line 1692

def prepare_save!
  run_before_save_callbacks
end

#relation_change_operations ⇒ Array

Generates an array with two entries for addition and removal operations. The first entry of the array will contain a hash of all the change operations regarding adding new relational objects. The second entry in the array is a hash of all the change operations regarding removing relation objects from this field.

Returns:

  • (Array) —

    an array with two hashes; the first is a hash of all the addition operations and the second hash, all the remove operations.



1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
# File 'lib/parse/model/core/actions.rb', line 1715

def relation_change_operations
  return [{}, {}] unless relation_changes?

  additions = []
  removals = []
  # go through all the additions of a collection and generate an action to add.
  relation_updates.each do |field, collection|
    if collection.additions.count > 0
      additions.push Parse::RelationAction.new(field, objects: collection.additions, polarity: true)
    end
    # go through all the additions of a collection and generate an action to remove.
    if collection.removals.count > 0
      removals.push Parse::RelationAction.new(field, objects: collection.removals, polarity: false)
    end
  end
  # merge all additions and removals into one large hash
  additions = additions.reduce({}) { |m, v| m.merge! v.as_json }
  removals = removals.reduce({}) { |m, v| m.merge! v.as_json }
  [additions, removals]
end

#save(session: nil, autoraise: false, force: false, validate: true) ⇒ Boolean

saves the object. If the object has not changed, it is a noop. If it is new, we will create the object. If the object has an id, we will update the record.

You may pass a session token to the session argument to perform this actions with the privileges of a certain user.

Callback order:

  1. before_validation / around_validation / after_validation
  2. before_save / around_save
  3. before_create or before_update / around_create or around_update
  4. [actual save operation]
  5. after_create or after_update
  6. after_save

You can define before and after :save callbacks autoraise: set to true will automatically raise an exception if the save fails

Parameters:

  • session (String) (defaults to: nil) —

    a session token in order to apply ACLs to this operation.

  • autoraise (Boolean) (defaults to: false) —

    whether to raise an exception if the save fails.

  • force (Boolean) (defaults to: false) —

    whether to run callbacks and send request even if there are no changes.

  • validate (Boolean) (defaults to: true) —

    whether to run validations (default: true).

Returns:

  • (Boolean) —

    whether the save was successful.

Raises:

  • (Parse::RecordNotSaved) —

    if the save fails

  • ArgumentError if a non-nil value is passed to session that doesn't provide a session token string.



1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
# File 'lib/parse/model/core/actions.rb', line 1549

def save(session: nil, autoraise: false, force: false, validate: true)
  # Prevent saving objects that have been fetched and found to be deleted
  if _deleted?
    error_msg = "Cannot save deleted object. Object with id '#{@id}' no longer exists on the server."
    raise Parse::Error::ProtocolError, error_msg
  end

  # A destroyed record is never recreated by a later save (ActiveRecord
  # returns false here too). Build a new object to write it again.
  if destroyed?
    if self.class.raise_on_save_failure || autoraise.present?
      raise Parse::RecordNotSaved.new(self), "Cannot save a destroyed #{parse_class} (id '#{@id}')."
    end
    return false
  end

  @_session_token = _validate_session_token! session, :save
  return true unless changed? || force

  # A create may assign the objectId client-side from a callback
  # (parse_reference precompute, acl_owner :self). Until the create
  # returns createdAt, persisted? must stay false for such an object.
  @_creating_record = true if @id.blank?
  _save_with_callbacks(autoraise: autoraise, force: force, validate: validate)
ensure
  remove_instance_variable(:@_creating_record) if defined?(@_creating_record)
end

#save!(session: nil, force: false) ⇒ Boolean

Save this object and raise an exception if it fails.

Parameters:

  • session (String) (defaults to: nil) —

    a session token in order to apply ACLs to this operation.

  • force (Boolean) (defaults to: false) —

    whether to run callbacks and send request even if there are no changes.

Returns:

  • (Boolean) —

    whether the save was successful.

Raises:

  • (Parse::RecordNotSaved) —

    if the save fails

  • ArgumentError if a non-nil value is passed to session that doesn't provide a session token string.



1642
1643
1644
# File 'lib/parse/model/core/actions.rb', line 1642

def save!(session: nil, force: false)
  save(autoraise: true, session: session, force: force)
end

#set_attributes!(hash, dirty_track = false) ⇒ Hash

Performs mass assignment using a hash with the ability to modify dirty tracking. This is an internal method used to set properties on the object while controlling whether they are dirty tracked. Each defined property has a method defined with the suffix _set_attribute! that can will be called if it is contained in the hash.

Examples:

object.set_attributes!( {"myField" => value}, false)

# equivalent to calling the specific method.
object.myField_set_attribute!(value, false)

Parameters:

  • hash (Hash) —

    the hash containing all the attribute names and values.

  • dirty_track (Boolean) (defaults to: false) —

    whether the assignment should be tracked in the change tracking system.

Returns:



1778
1779
1780
1781
1782
1783
1784
1785
# File 'lib/parse/model/core/actions.rb', line 1778

def set_attributes!(hash, dirty_track = false)
  return unless hash.is_a?(Hash)
  hash.each do |k, v|
    next if k == Parse::Model::OBJECT_ID || k == Parse::Model::ID
    method = "#{k}_set_attribute!"
    send(method, v, dirty_track) if respond_to?(method)
  end
end

#update(force: false) ⇒ Boolean

Save all the changes related to this object.

Parameters:

  • force (Boolean) (defaults to: false) —

    whether to send the update even if there are no changes.

Returns:

  • (Boolean) —

    true/false whether it was successful.



1443
1444
1445
1446
# File 'lib/parse/model/core/actions.rb', line 1443

def update(force: false)
  return true unless attribute_changes? || force
  update!(force: force)
end

#update!(raw: false, force: false) ⇒ Boolean

This methods sends an update request for this object with the any change information based on its local attributes. The bang implies that it will send the request even though it is possible no changes were performed. This is useful in kicking-off an beforeSave / afterSave hooks Save the object regardless of whether there are changes. This would call any beforeSave and afterSave cloud code hooks you have registered for this class.

Returns:

  • (Boolean) —

    true/false whether it was successful.



1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
# File 'lib/parse/model/core/actions.rb', line 1411

def update!(raw: false, force: false)
  if valid? == false
    errors.full_messages.each do |msg|
      warn "[#{parse_class}] warning: #{msg}"
    end
  end
  if force == true && attribute_changes?.blank? && !new?
    # if we are forcing an update, but there are no attribute changes,
    # we should still mark the updated_at field as changed so that
    # the server updates it.
    if self.class.fields[:updated_at].present?
      self.updated_at = Time.now.utc
      self.updated_at_will_change! if respond_to?(:updated_at_will_change!)
    end
  end
  return false unless _check_unsaved_references
  response = client.update_object(parse_class, id, attribute_updates, session_token: _session_token)
  @_last_response = response
  if response.success?
    result = response.result
    # Because beforeSave hooks can change the fields we are saving, any items that were
    # changed, are returned to us and we should apply those locally to be in sync.
    set_attributes!(result)
  end
  puts "Error updating #{self.parse_class}: #{response.error}" if response.error?
  return response if raw
  response.success?
end

#update_relations ⇒ Boolean

Saves and updates all the relational changes for made to this object.

Returns:

  • (Boolean) —

    whether all the save or update requests were successful.



1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
# File 'lib/parse/model/core/actions.rb', line 1738

def update_relations
  # relational saves require an id
  return false unless @id.present?
  # verify we have relational changes before we do work.
  return true unless relation_changes?
  raise "Unable to update relations for a new object." if new?
  # get all the relational changes (both additions and removals)
  additions, removals = relation_change_operations

  responses = []
  # Send parallel Parse requests for each of the items to update.
  # since we will have multiple responses, we will track it in array
  [removals, additions].threaded_each do |ops|
    next if ops.empty? #if no operations to be performed, then we are done
    responses << client.update_object(parse_class, @id, ops, session_token: _session_token)
  end
  # check if any of them ended up in error
  has_error = responses.any? { |response| response.error? }
  # if everything was ok, find the last response to be returned and update
  #their fields in case beforeSave made any changes.
  unless has_error || responses.empty?
    result = responses.last.result #last result to come back
    set_attributes!(result)
  end #unless
  has_error == false
end

#uri_path ⇒ String

Returns the API uri path for this class.

Returns:

  • (String) —

    the API uri path for this class.



1289
1290
1291
# File 'lib/parse/model/core/actions.rb', line 1289

def uri_path
  self.client.url_prefix.path + Client.uri_path(self)
end