Module: Candy::Crunch::Document

Included in:
Piece
Defined in:
lib/candy/crunch/document.rb

Overview

MongoDB interface methods specific to the handling of individual documents (as opposed to collections or cursors).

Instance Method Summary collapse

Instance Method Details

#inc(field, value = 1) ⇒ Object

Increments the specified field by the specified amount (defaults to 1) and returns the new value.



55
56
57
58
# File 'lib/candy/crunch/document.rb', line 55

def inc(field, value=1)
  operate :inc, field => value
  retrieve(field)[field]
end

#inc!(field, value = 1) ⇒ Object

Increments the specified field by the specified amount (defaults to 1). Does not return the new value or any document errors.



49
50
51
# File 'lib/candy/crunch/document.rb', line 49

def inc!(field, value=1)
  operate! :inc, field: value
end

#operate(operator, fields, options = {safe: true}) ⇒ Object

A generic updater that performs the atomic operation specified on a value nested arbitrarily deeply.



23
24
25
26
27
28
29
30
# File 'lib/candy/crunch/document.rb', line 23

def operate(operator, fields, options={safe: true})
  if @__candy_parent
    @__candy_parent.operate operator, embedded(fields), options
  else
    @__candy_id = collection.insert({}) unless id   # Ensure we have something to update
    collection.update({'_id' => id}, {"$#{operator}" => Wrapper.wrap(fields)}, options)
  end
end

#operate!(operator, fields) ⇒ Object

A generic updater that performs the atomic operation specified on a value nested arbitrarily deeply. Operates in “unsafe” mode, meaning that no document errors will be returned and results are not guaranteed. The benefit is that it’s very, very fast. Always returns true.



17
18
19
# File 'lib/candy/crunch/document.rb', line 17

def operate!(operator, fields)
  operate operator, fields, {safe: false} and true
end

#retrieve(*fields) ⇒ Object

RETRIEVAL METHODS Returns the listed fields of the document. If no fields are given, returns the whole document.



8
9
10
11
# File 'lib/candy/crunch/document.rb', line 8

def retrieve(*fields)
  options = (fields.empty? ? {} : {fields: fields})
  from_candy(collection.find_one({'_id' => id}, options)) if id
end

#set(fields) ⇒ Object

Given a hash of property/value pairs, sets those values in Mongo using the atomic $set if we have a document ID. Otherwise inserts them and sets the object’s ID. Returns the values passed to it.



42
43
44
45
# File 'lib/candy/crunch/document.rb', line 42

def set(fields)
  operate :set, fields
  fields
end

#set!(fields) ⇒ Object

Given a hash of property/value pairs, sets those values in Mongo using the atomic $set if we have a document ID. Otherwise inserts them and sets the object’s ID. Operates in ‘unsafe’ mode, so database exceptions are not reported but updates are very fast.



35
36
37
# File 'lib/candy/crunch/document.rb', line 35

def set!(fields)
  operate! :set, fields
end