Class: Mongoid::Persistence::Atomic::AddToSet

Inherits:
Object
  • Object
show all
Includes:
Operation
Defined in:
lib/mongoid/persistence/atomic/add_to_set.rb

Overview

This class provides the ability to perform an explicit $addToSet modification on a specific field.

Instance Attribute Summary

Attributes included from Operation

#document, #fields, #options, #value

Instance Method Summary collapse

Methods included from Operation

#collection, #initialize, #path, #prepare

Methods included from Atomic::Positionable

#positionally

Instance Method Details

#operation(modifier) ⇒ Hash

Get the atomic operation to perform.

Examples:

Get the operation.

add_to_set.operation("$addToSet")

Parameters:

  • modifier (String)

    The modifier to use.

Returns:

  • (Hash)

    The atomic operation for the field and addition.

Since:

  • 2.0.0



41
42
43
# File 'lib/mongoid/persistence/atomic/add_to_set.rb', line 41

def operation(modifier)
  { modifier => { path => value.is_a?(Array) ? { "$each" => value } : value}}
end

#persistObject

Sends the atomic $addToSet operation to the database.

Examples:

Persist the new values.

addToSet.persist

Returns:

  • (Object)

    The new array value.

Since:

  • 2.0.0



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mongoid/persistence/atomic/add_to_set.rb', line 19

def persist
  prepare do
    document[field] = [] unless document[field]
    values = document.send(field)
    Array.wrap(value).each do |val|
      values.push(val) unless values.include?(val)
    end
    execute("$addToSet")
    values
  end
end