Module: BSON::Hash

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

Instance Method Summary collapse

Instance Method Details

#to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?) ⇒ BSON::ByteBuffer

Get the hash as encoded BSON.

Examples:

Get the hash as encoded BSON.

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

Returns:

See Also:

Since:

  • 2.0.0



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/bson/hash.rb', line 40

def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
  if buffer.respond_to?(:put_hash)
    buffer.put_hash(self, validating_keys)
  else
    position = buffer.length
    buffer.put_int32(0)
    each do |field, value|
      buffer.put_byte(value.bson_type)
      buffer.put_cstring(field.to_bson_key(validating_keys))
      value.to_bson(buffer, validating_keys)
    end
    buffer.put_byte(NULL_BYTE)
    buffer.replace_int32(position, buffer.length - position)
  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



64
65
66
# File 'lib/bson/hash.rb', line 64

def to_bson_normalized_value
  Document.new(self)
end