Module: BSON::Array

Defined in:
lib/bson/array.rb

Overview

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

See Also:

Since:

  • 2.0.0

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

BSON_TYPE =

An array is type 0x04 in the BSON spec.

Since:

  • 2.0.0

::String.new(4.chr, encoding: BINARY).freeze

Instance Method Summary collapse

Instance Method Details

#as_extended_json(**options) ⇒ Array

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.

Parameters:

  • opts (Hash)

    a customizable set of options

Returns:

  • (Array)

    This array converted to extended json representation.

Since:

  • 2.0.0



104
105
106
107
108
# File 'lib/bson/array.rb', line 104

def as_extended_json(**options)
  map do |item|
    item.as_extended_json(**options)
  end
end

#to_bson(buffer = ByteBuffer.new) ⇒ BSON::ByteBuffer

Note:

Arrays are encoded as documents, where the index of the value in the array is the actual key.

Get the array as encoded BSON.

Examples:

Get the array as encoded BSON.

[ 1, 2, 3 ].to_bson

Returns:

See Also:

Since:

  • 2.0.0



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/bson/array.rb', line 44

def to_bson(buffer = ByteBuffer.new)
  if buffer.respond_to?(:put_array)
    buffer.put_array(self)
  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)
    end
    buffer.put_byte(NULL_BYTE)
    buffer.replace_int32(position, buffer.length - position)
  end
end

#to_bson_normalized_valueArray

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

Examples:

Convert the array to a normalized value.

array.to_bson_normalized_value

Returns:

  • (Array)

    The normalized array.

Since:

  • 3.0.0



90
91
92
# File 'lib/bson/array.rb', line 90

def to_bson_normalized_value
  map(&:to_bson_normalized_value)
end

#to_bson_object_idString

Note:

This is used for repairing legacy bson data.

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

Examples:

Convert the array to an object id.

array.to_bson_object_id

Returns:

  • (String)

    The raw object id bytes.

Raises:

Since:

  • 2.0.0



78
79
80
# File 'lib/bson/array.rb', line 78

def to_bson_object_id
  ObjectId.repair(self) { pack('C*') }
end