Module: BSON::String

Defined in:
lib/bson/string.rb

Overview

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

See Also:

Since:

  • 2.0.0

Defined Under Namespace

Modules: ClassMethods Classes: IllegalKey

Constant Summary collapse

BSON_TYPE =

A string is type 0x02 in the BSON spec.

Since:

  • 2.0.0

2.chr.force_encoding(BINARY).freeze
ILLEGAL_KEY =

Regex for matching illegal BSON keys.

Since:

  • 4.1.0

/(\A[$])|(\.)/.freeze

Instance Method Summary collapse

Instance Method Details

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

Get the string as encoded BSON.

Examples:

Get the string as encoded BSON.

"test".to_bson

Raises:

  • (EncodingError)

    If the string is not UTF-8.

See Also:

Since:

  • 2.0.0


48
49
50
# File 'lib/bson/string.rb', line 48

def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
  buffer.put_string(self)
end

#to_bson_key(validating_keys = Config.validating_keys?) ⇒ String

Get the string as a BSON key name encoded C string with checking for special characters.

Examples:

Get the string as key name.

"test".to_bson_key

Raises:

  • (EncodingError)

    If the string is not UTF-8.

  • (IllegalKey)

    If validating keys and it contains a '.' or starts with '$'.

See Also:

Since:

  • 2.0.0


67
68
69
70
71
72
# File 'lib/bson/string.rb', line 67

def to_bson_key(validating_keys = Config.validating_keys?)
  if validating_keys
    raise IllegalKey.new(self) if ILLEGAL_KEY =~ self
  end
  self
end

#to_bson_object_idString

Note:

This is used for repairing legacy bson data.

Convert the string to an object id. This will only work for strings of size 12.

Examples:

Convert the string to an object id.

string.to_bson_object_id

Raises:

Since:

  • 2.0.0


87
88
89
# File 'lib/bson/string.rb', line 87

def to_bson_object_id
  ObjectId.repair(self)
end

#to_hex_stringString

Convert the string to a hexidecimal representation.

Examples:

Convert the string to hex.

"\x01".to_hex_string

Since:

  • 2.0.0


99
100
101
# File 'lib/bson/string.rb', line 99

def to_hex_string
  unpack("H*")[0]
end