Class: BSON::CodeWithScope

Inherits:
Object
  • Object
show all
Includes:
JSON
Defined in:
lib/bson/code_with_scope.rb

Overview

Represents a code with scope, which is a wrapper around javascript code with variable scope provided.

See Also:

Since:

  • 2.0.0

Constant Summary collapse

BSON_TYPE =

A code with scope is type 0x0F in the BSON spec.

Since:

  • 2.0.0

15.chr.force_encoding(BINARY).freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from JSON

#to_json

Constructor Details

#initialize(javascript = "", scope = {}) ⇒ CodeWithScope

Instantiate the new code with scope.

Examples:

Instantiate the code with scope.

BSON::CodeWithScope.new("this.value = name", name: "sid")

Since:

  • 2.0.0


75
76
77
78
# File 'lib/bson/code_with_scope.rb', line 75

def initialize(javascript = "", scope = {})
  @javascript = javascript
  @scope = scope
end

Instance Attribute Details

#javascriptString

Returns The javascript code.

Since:

  • 2.0.0


37
38
39
# File 'lib/bson/code_with_scope.rb', line 37

def javascript
  @javascript
end

#scopeObject

Since:

  • 2.0.0


37
# File 'lib/bson/code_with_scope.rb', line 37

attr_reader :javascript, :scope

Class Method Details

.from_bson(buffer) ⇒ TrueClass, FalseClass

Deserialize a code with scope from BSON.

See Also:

Since:

  • 2.0.0


107
108
109
110
# File 'lib/bson/code_with_scope.rb', line 107

def self.from_bson(buffer)
  buffer.get_int32 # Throw away the total length.
  new(buffer.get_string, ::Hash.from_bson(buffer))
end

Instance Method Details

#==(other) ⇒ true, false

Determine if this code with scope object is equal to another object.

Examples:

Check the code with scope equality.

code_with_scope == other

Since:

  • 2.0.0


49
50
51
52
# File 'lib/bson/code_with_scope.rb', line 49

def ==(other)
  return false unless other.is_a?(CodeWithScope)
  javascript == other.javascript && scope == other.scope
end

#as_json(*args) ⇒ Hash

Get the code with scope as JSON hash data.

Examples:

Get the code with scope as a JSON hash.

code_with_scope.as_json

Since:

  • 2.0.0


62
63
64
# File 'lib/bson/code_with_scope.rb', line 62

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

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

Encode the javascript code with scope.

Examples:

Encode the code with scope.

code_with_scope.to_bson

See Also:

Since:

  • 2.0.0


90
91
92
93
94
95
96
# File 'lib/bson/code_with_scope.rb', line 90

def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
  position = buffer.length
  buffer.put_int32(0)
  buffer.put_string(javascript)
  scope.to_bson(buffer)
  buffer.replace_int32(position, buffer.length - position)
end