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

4.chr.force_encoding(BINARY).freeze

Instance Method Summary collapse

Instance Method Details

#to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?) ⇒ 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:

  • (BSON::ByteBuffer)

    The buffer with the encoded object.

See Also:

Since:

  • 2.0.0



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/bson/array.rb', line 43

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|
      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_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



84
85
86
# File 'lib/bson/array.rb', line 84

def to_bson_normalized_value
  map { |value| value.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



72
73
74
# File 'lib/bson/array.rb', line 72

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