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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
# encoding: utf-8
module Origin
# The options is a hash representation of options passed to MongoDB queries,
# such as skip, limit, and sorting criteria.
class Options < Smash
# Convenience method for getting the field options.
#
# @example Get the fields options.
# options.fields
#
# @return [ Hash ] The fields options.
#
# @since 1.0.0
def fields
self[:fields]
end
# Convenience method for getting the limit option.
#
# @example Get the limit option.
# options.limit
#
# @return [ Integer ] The limit option.
#
# @since 1.0.0
def limit
self[:limit]
end
# Convenience method for getting the skip option.
#
# @example Get the skip option.
# options.skip
#
# @return [ Integer ] The skip option.
#
# @since 1.0.0
def skip
self[:skip]
end
# Convenience method for getting the sort options.
#
# @example Get the sort options.
# options.sort
#
# @return [ Hash ] The sort options.
#
# @since 1.0.0
def sort
self[:sort]
end
# Store the value in the options for the provided key. The options will
# handle all necessary serialization and localization in this step.
#
# @example Store a value in the options.
# options.store(:key, "testing")
#
# @param [ String, Symbol ] key The name of the attribute.
# @param [ Object ] value The value to add.
#
# @return [ Object ] The stored object.
#
# @since 1.0.0
def store(key, value)
super(key, evolve(value))
end
alias :[]= :store
# Convert the options to aggregation pipeline friendly options.
#
# @example Convert the options to a pipeline.
# options.to_pipeline
#
# @return [ Array<Hash> ] The options in pipeline form.
#
# @since 2.0.0
def to_pipeline
pipeline = []
pipeline.push({ "$skip" => skip }) if skip
pipeline.push({ "$limit" => limit }) if limit
pipeline.push({ "$sort" => sort }) if sort
pipeline
end
private
# Evolve a single key selection with various types of values.
#
# @api private
#
# @example Evolve a simple selection.
# options.evolve(field, 5)
#
# @param [ Object ] value The value to serialize.
#
# @return [ Object ] The serialized object.
#
# @since 1.0.0
def evolve(value)
case value
when Hash
evolve_hash(value)
else
value
end
end
# Evolve a single key selection with hash values.
#
# @api private
#
# @example Evolve a simple selection.
# options.evolve(field, { "$gt" => 5 })
#
# @param [ Hash ] value The hash to serialize.
#
# @return [ Object ] The serialized hash.
#
# @since 1.0.0
def evolve_hash(value)
value.inject({}) do |hash, (field, _value)|
name, serializer = storage_pair(field)
hash[normalized_key(name, serializer)] = _value
hash
end
end
end
end
|