Module: Mongoid::Persistable::Incrementable

Extended by:
ActiveSupport::Concern
Included in:
Mongoid::Persistable
Defined in:
lib/mongoid/persistable/incrementable.rb

Overview

Defines behaviour for $inc operations.

Since:

  • 4.0.0

Instance Method Summary collapse

Instance Method Details

#inc(increments) ⇒ true, false

Increment the provided fields by the corresponding values. Values can be positive or negative, and if no value exists for the field it will be set with the provided value.

Examples:

Increment the fields.

document.inc(score: 10, place: 1, lives: -10)

Parameters:

  • increments (Hash)

    The field/inc increment pairs.

Returns:

  • (true, false)

    If the increment succeeded.

Since:

  • 4.0.0



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/mongoid/persistable/incrementable.rb', line 23

def inc(increments)
  prepare_atomic_operation do |ops|
    process_atomic_operations(increments) do |field, value|
      increment = value.__to_inc__
      current = attributes[field]
      attributes[field] = (current || 0) + increment
      ops[atomic_attribute_name(field)] = increment
    end
    { "$inc" => ops }
  end
end