module BSON::Array

Injects behaviour for encoding and decoding arrays to and from raw bytes as specified by the BSON spec.

@see bsonspec.org/#/specification

@since 2.0.0

Constants

BSON_TYPE

An array is type 0x04 in the BSON spec.

@since 2.0.0

Public Instance Methods

as_extended_json(**options) click to toggle source

Converts this object to a representation directly serializable to Extended JSON (github.com/mongodb/specifications/blob/master/source/extended-json.rst).

This method recursively invokes as_extended_json with the provided options on each array element.

@option opts [ nil | :relaxed | :legacy ] :mode Serialization mode

(default is canonical extended JSON)

@return [ Array ] This array converted to extended json representation.

# File lib/bson/array.rb, line 102
def as_extended_json(**options)
  map do |item|
    item.as_extended_json(**options)
  end
end
to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?) click to toggle source

Get the array as encoded BSON.

@example Get the array as encoded BSON.

[ 1, 2, 3 ].to_bson

@note Arrays are encoded as documents, where the index of the value in

the array is the actual key.

@return [ BSON::ByteBuffer ] The buffer with the encoded object.

@see bsonspec.org/#/specification

@since 2.0.0

# File lib/bson/array.rb, line 44
def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
  if buffer.respond_to?(:put_array)
    buffer.put_array(self, validating_keys)
  else
    position = buffer.length
    buffer.put_int32(0)
    each_with_index do |value, index|
      unless value.respond_to?(:bson_type)
        raise Error::UnserializableClass, "Array element at position #{index} does not define its BSON serialized type: #{value}"
      end
      buffer.put_byte(value.bson_type)
      buffer.put_cstring(index.to_s)
      value.to_bson(buffer, validating_keys)
    end
    buffer.put_byte(NULL_BYTE)
    buffer.replace_int32(position, buffer.length - position)
  end
end
to_bson_normalized_value() click to toggle source

Converts the array to a normalized value in a BSON document.

@example Convert the array to a normalized value.

array.to_bson_normalized_value

@return [ Array ] The normalized array.

@since 3.0.0

# File lib/bson/array.rb, line 88
def to_bson_normalized_value
  map { |value| value.to_bson_normalized_value }
end
to_bson_object_id() click to toggle source

Convert the array to an object id. This will only work for arrays of size 12 where the elements are all strings.

@example Convert the array to an object id.

array.to_bson_object_id

@note This is used for repairing legacy bson data.

@raise [ BSON::ObjectId::Invalid ] If the array is not 12 elements.

@return [ String ] The raw object id bytes.

@since 2.0.0

# File lib/bson/array.rb, line 76
def to_bson_object_id
  ObjectId.repair(self) { pack("C*") }
end