forked from mongodb/mongoid
/
array.rb
86 lines (80 loc) · 2.56 KB
/
array.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# encoding: utf-8
module Mongoid #:nodoc:
module Fields #:nodoc:
module Internal #:nodoc:
# Defines the behaviour for array fields.
class Array
include Serializable
# Adds the atomic changes for this type of resizable field.
#
# @example Add the atomic changes.
# field.add_atomic_changes(doc, "key", {}, [], [])
#
# @param [ Document ] document The document to add to.
# @param [ String ] name The name of the field.
# @param [ String ] key The atomic location of the field.
# @param [ Hash ] mods The current modifications.
# @param [ Array ] new The new elements to add.
# @param [ Array ] old The old elements getting removed.
#
# @since 2.4.0
def add_atomic_changes(document, name, key, mods, new, old)
pushes = (new || []) - (old || [])
pulls = (old || []) - (new || [])
if old.nil?
mods[key] = pushes
elsif !pushes.empty? && !pulls.empty?
mods[key] = document.attributes[name]
elsif !pushes.empty?
document.atomic_array_pushes[key] = pushes
elsif !pulls.empty?
document.atomic_array_pulls[key] = pulls
end
end
# Array fields are resizable.
#
# @example Is this field resizable?
# field.resizable?
#
# @return [ true ] Always true.
#
# @since 2.4.0
def resizable?; true; end
# Serialize the object from the type defined in the model to a MongoDB
# compatible object to store.
#
# @example Serialize the field.
# field.serialize(object)
#
# @param [ Object ] object The object to cast.
#
# @return [ Array ] The converted object.
#
# @since 2.1.0
def serialize(object)
raise_or_return(object)
end
protected
# If the value is not an array or nil we will raise an error,
# otherwise return the value.
#
# @example Raise or return the value.
# field.raise_or_return([])
#
# @param [ Object ] value The value to check.a
#
# @raise [ InvalidType ] If not passed an array.
#
# @return [ Array ] The array.
#
# @since 2.1.0
def raise_or_return(value)
unless value.nil? || value.is_a?(::Array)
raise Mongoid::Errors::InvalidType.new(::Array, value)
end
value
end
end
end
end
end