Class: Mongoid::Persistence::Atomic::AddToSet
- 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, #field, #options, #value
Instance Method Summary collapse
-
#operation(modifier) ⇒ Hash
Get the atomic operation to perform.
-
#persist ⇒ Object
Sends the atomic $addToSet operation to the database.
Methods included from Operation
#collection, #initialize, #path, #prepare
Instance Method Details
#operation(modifier) ⇒ Hash
Get the atomic operation to perform.
45 46 47 |
# File 'lib/mongoid/persistence/atomic/add_to_set.rb', line 45 def operation(modifier) { modifier => { path => value.is_a?(Array) ? { "$each" => value } : value}} end |
#persist ⇒ Object
Sends the atomic $addToSet operation to the database.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# 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 values.tap do if document.persisted? collection.update(document.atomic_selector, operation("$addToSet"), ) document.remove_change(field) end end end end |