Module: BSON::Hash

Includes:
Encodable
Defined in:
lib/bson/hash.rb

Overview

Injects behaviour for encoding and decoding hashes 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 hash (embedded document) is type 0x03 in the BSON spec.

Since:

  • 2.0.0

3.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

Get the hash as encoded BSON.

Examples:

Get the hash as encoded BSON.

{ "field" => "value" }.to_bson

Returns:

  • (String)

    The encoded string.

See Also:

Since:

  • 2.0.0



41
42
43
44
45
46
47
48
49
# File 'lib/bson/hash.rb', line 41

def to_bson(encoded = ''.force_encoding(BINARY))
  encode_with_placeholder_and_null(BSON_ADJUST, encoded) do |encoded|
    each do |field, value|
      encoded << value.bson_type
      field.to_bson_key(encoded)
      value.to_bson(encoded)
    end
  end
end

#to_bson_normalized_valueBSON::Document

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

Examples:

Convert the hash to a normalized value.

hash.to_bson_normalized_value

Returns:

Since:

  • 3.0.0



59
60
61
# File 'lib/bson/hash.rb', line 59

def to_bson_normalized_value
  Document.new(self)
end