Module: BSON::Array

Includes:
Encodable
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

Constants included from Encodable

Encodable::BSON_ADJUST, Encodable::PLACEHOLDER, Encodable::STRING_ADJUST

Instance Method Summary collapse

Methods included from Encodable

#encode_binary_data_with_placeholder, #encode_with_placeholder_and_null

Instance Method Details

#to_bson(encoded = ''.force_encoding(BINARY)) ⇒ String

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:

  • (String)

    The encoded string.

See Also:

Since:

  • 2.0.0



44
45
46
47
48
49
50
51
52
# File 'lib/bson/array.rb', line 44

def to_bson(encoded = ''.force_encoding(BINARY))
  encode_with_placeholder_and_null(BSON_ADJUST, encoded) do |encoded|
    each_with_index do |value, index|
      encoded << value.bson_type
      index.to_bson_key(encoded)
      value.to_bson(encoded)
    end
  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 normazlied array.

Since:

  • 3.0.0



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

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:

  • (InvalidObjectId)

    If the array is not 12 elements.

Since:

  • 2.0.0



67
68
69
# File 'lib/bson/array.rb', line 67

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