class BSON::Code

Represents a code type, which is a wrapper around javascript code.

@see bsonspec.org/#/specification

@since 2.0.0

Constants

BSON_TYPE

A code is type 0x0D in the BSON spec.

@since 2.0.0

Attributes

javascript[R]

@!attribute javascript

@return [ String ] The javascript code.
@since 2.0.0

Public Class Methods

from_bson(buffer, **options) click to toggle source

Deserialize code from BSON.

@param [ ByteBuffer ] buffer The byte buffer.

@option options [ nil | :bson ] :mode Decoding mode to use.

@return [ TrueClass, FalseClass ] The decoded code.

@see bsonspec.org/#/specification

@since 2.0.0

# File lib/bson/code.rb, line 110
def self.from_bson(buffer, **options)
  new(buffer.get_string)
end
new(javascript = "") click to toggle source

Instantiate the new code.

@example Instantiate the new code.

BSON::Code.new("this.value = 5")

@param [ String ] javascript The javascript code.

@since 2.0.0

# File lib/bson/code.rb, line 81
def initialize(javascript = "")
  @javascript = javascript
end

Public Instance Methods

==(other) click to toggle source

Determine if this code object is equal to another object.

@example Check the code equality.

code == other

@param [ Object ] other The object to compare against.

@return [ true, false ] If the objects are equal.

@since 2.0.0

# File lib/bson/code.rb, line 47
def ==(other)
  return false unless other.is_a?(Code)
  javascript == other.javascript
end
as_extended_json(**_options) click to toggle source

Converts this object to a representation directly serializable to Extended JSON (github.com/mongodb/specifications/blob/master/source/extended-json.rst).

@option opts [ nil | :relaxed | :legacy ] :mode Serialization mode

(default is canonical extended JSON)

@return [ Hash ] The extended json representation.

# File lib/bson/code.rb, line 69
def as_extended_json(**_options)
  { "$code" => javascript }
end
as_json(*_args) click to toggle source

Return a representation of the object for use in application-level JSON serialization. Since BSON::Code is used exclusively in BSON-related contexts, this method returns the canonical Extended JSON representation.

@return [ Hash ] The extended json representation.

# File lib/bson/code.rb, line 58
def as_json(*_args)
  as_extended_json
end
to_bson(buffer = ByteBuffer.new) click to toggle source

Encode the javascript code.

@example Encode the code.

code.to_bson

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

@see bsonspec.org/#/specification

@since 2.0.0

# File lib/bson/code.rb, line 95
def to_bson(buffer = ByteBuffer.new)
  buffer.put_string(javascript) # @todo: was formerly to_bson_string
end