Class: BSON::Code

Inherits:
Object
  • Object
show all
Includes:
Encodable, JSON
Defined in:
lib/bson/code.rb

Overview

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

See Also:

Since:

  • 2.0.0

Constant Summary collapse

BSON_TYPE =

A code is type 0x0D in the BSON spec.

Since:

  • 2.0.0

13.chr.force_encoding(BINARY).freeze

Constants included from Encodable

Encodable::BSON_ADJUST, Encodable::PLACEHOLDER, Encodable::STRING_ADJUST

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Encodable

#encode_binary_data_with_placeholder, #encode_with_placeholder_and_null

Methods included from JSON

#to_json

Constructor Details

#initialize(javascript = "") ⇒ Code

Instantiate the new code.

Examples:

Instantiate the new code.

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

Parameters:

  • javascript (String) (defaults to: "")

    The javascript code.

Since:

  • 2.0.0



71
72
73
# File 'lib/bson/code.rb', line 71

def initialize(javascript = "")
  @javascript = javascript
end

Instance Attribute Details

#javascriptObject

Since:

  • 2.0.0



34
35
36
# File 'lib/bson/code.rb', line 34

def javascript
  @javascript
end

Class Method Details

.from_bson(bson) ⇒ TrueClass, FalseClass

Deserialize code from BSON.

Parameters:

  • bson (BSON)

    The encoded code.

Returns:

See Also:

Since:

  • 2.0.0



100
101
102
# File 'lib/bson/code.rb', line 100

def self.from_bson(bson)
  new(bson.read(Int32.from_bson(bson)).from_bson_string.chop!)
end

Instance Method Details

#==(other) ⇒ true, false

Determine if this code object is equal to another object.

Examples:

Check the code equality.

code == other

Parameters:

  • other (Object)

    The object to compare against.

Returns:

  • (true, false)

    If the objects are equal.

Since:

  • 2.0.0



46
47
48
49
# File 'lib/bson/code.rb', line 46

def ==(other)
  return false unless other.is_a?(Code)
  javascript == other.javascript
end

#as_json(*args) ⇒ Hash

Get the code as JSON hash data.

Examples:

Get the code as a JSON hash.

code.as_json

Returns:

  • (Hash)

    The code as a JSON hash.

Since:

  • 2.0.0



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

def as_json(*args)
  { "$code" => javascript }
end

#to_bson(encoded = ''.force_encoding(BINARY)) ⇒ String

Encode the javascript code.

Examples:

Encode the code.

code.to_bson

Returns:

  • (String)

    The encoded string.

See Also:

Since:

  • 2.0.0



85
86
87
88
89
# File 'lib/bson/code.rb', line 85

def to_bson(encoded = ''.force_encoding(BINARY))
  encode_with_placeholder_and_null(STRING_ADJUST, encoded) do |encoded|
    javascript.to_bson_string(encoded)
  end
end