module BSON::String

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

@see bsonspec.org/#/specification

@since 2.0.0

Constants

BSON_TYPE

A string is type 0x02 in the BSON spec.

@since 2.0.0

ILLEGAL_KEY

Regex for matching illegal BSON keys.

@since 4.1.0

Public Instance Methods

to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?) click to toggle source

Get the string as encoded BSON.

@example Get the string as encoded BSON.

"test".to_bson

@raise [ EncodingError ] If the string is not UTF-8.

@return [ BSON::ByteBuffer ] The buffer with the encoded object.

@see bsonspec.org/#/specification

@since 2.0.0

# File lib/bson/string.rb, line 47
def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
  buffer.put_string(self)
end
to_bson_key(validating_keys = Config.validating_keys?) click to toggle source

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

@example Get the string as key name.

"test".to_bson_key

@raise [ EncodingError ] If the string is not UTF-8.

@raise [ IllegalKey ] If validating keys and it contains a '.' or starts

with '$'.

@return [ String ] The encoded string.

@see bsonspec.org/#/specification

@since 2.0.0

# File lib/bson/string.rb, line 66
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_id() click to toggle source

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

@example Convert the string to an object id.

string.to_bson_object_id

@note This is used for repairing legacy bson data.

@raise [ BSON::ObjectId::Invalid ] If the string is not 12 elements.

@return [ String ] The raw object id bytes.

@since 2.0.0

# File lib/bson/string.rb, line 86
def to_bson_object_id
  ObjectId.repair(self)
end
to_hex_string() click to toggle source

Convert the string to a hexidecimal representation.

@example Convert the string to hex.

"\x01".to_hex_string

@return [ String ] The string as hex.

@since 2.0.0

# File lib/bson/string.rb, line 98
def to_hex_string
  unpack("H*")[0]
end