class JS::Object
A JS::Object
represents a JavaScript object. Note that JS::Object
can represent a JavaScript object that represents a Ruby object (RbValue).
Example¶ ↑
A simple object access:
require 'js' document = JS.global[:document] # => # [object HTMLDocument] document[:title] # => "Hello, world!" document[:title] = "Hello, Ruby!" document.write("Hello, world!") # is equivalent to the following: document.call(:write, "Hello, world!") js_obj = JS.eval(<<-JS) return { method1: function(str, num) { // str is a JavaScript string and num is a JavaScript number. return str.length + num }, method2: function(rbObject) { // Call String#upcase method for the given Ruby object (RbValue). return rbObject.call("upcase").toString(); } } JS # Non JS::Object args are automatically converted to JS::Object by `to_js`. js_obj.method1("Hello", 5) # => 10 js_obj.method2(JS::Object.wrap("Hello, Ruby")) # => "HELLO, RUBY" (JS::Object)
Inherit BasicObject to prevent define coventional menthods. Override the ‘Object#send` to give priority to `send` method of JavaScript.
This is to make it easier to use JavaScript Objects with ‘send` method such as `WebSocket` and `XMLHttpRequest`. The JavaScript method call short-hand in `JS::Object` is implemented using `method_missing`. If JS::Object
inherits from Object
, the `send` method defined in Ruby will take precedence over the JavaScript `send` method. If you want to call the JavaScript `send` method, you must use the `call` method as follows:
ws = JS.global[:WebSocket].new("ws://example.com") ws.call(:send, ["Hello, world! from Ruby"])
This inheritation allows you to call the JavaScript ‘send` method with the following syntax:
ws.send("Hello, world! from Ruby")
Public Class Methods
Returns obj
wrapped by JS
class RbValue.
static VALUE _rb_js_obj_wrap(VALUE obj, VALUE wrapping) { #ifdef JS_ENABLE_COMPONENT_MODEL rb_abi_stage_rb_value_to_js(wrapping); return jsvalue_s_new(rb_js_abi_host_rb_object_to_js_rb_value()); #else rb_abi_lend_object(wrapping); return jsvalue_s_new( rb_js_abi_host_rb_object_to_js_rb_value((uint32_t)wrapping)); #endif }
Public Instance Methods
Performs “==” comparison, a.k.a the “Abstract Equality Comparison” algorithm defined in the ECMAScript. 262.ecma-international.org/11.0/#sec-abstract-equality-comparison If the given other object is not a JS::Object
, try to convert it to a JS::Object
using JS.try_convert
. If the conversion fails, returns false.
Returns the value of the property:
JS.global[:Object] JS.global[:console][:log]
static VALUE _rb_js_obj_aref(VALUE obj, VALUE key) { struct jsvalue *p = check_jsvalue(obj); rb_js_abi_host_string_t key_abi_str; key = rb_obj_as_string(key); rstring_to_abi_string(key, &key_abi_str); rb_js_abi_host_js_abi_result_t ret; rb_js_abi_host_reflect_get(p->abi, &key_abi_str, &ret); raise_js_error_if_failure(&ret); return jsvalue_s_new(ret.val.success); }
Set a property on the object with the given value. Returns the value of the property:
JS.global[:Object][:foo] = "bar" p JS.global[:console][:foo] # => "bar"
static VALUE _rb_js_obj_aset(VALUE obj, VALUE key, VALUE val) { struct jsvalue *p = check_jsvalue(obj); VALUE rv = _rb_js_try_convert(rb_mJS, val); if (rv == Qnil) { rb_raise(rb_eTypeError, "wrong argument type %s (expected JS::Object like object)", rb_class2name(rb_obj_class(val))); } struct jsvalue *v = check_jsvalue(rv); rb_js_abi_host_string_t key_abi_str; key = rb_obj_as_string(key); rstring_to_abi_string(key, &key_abi_str); rb_js_abi_host_js_abi_result_t ret; rb_js_abi_host_reflect_set(p->abi, &key_abi_str, v->abi, &ret); raise_js_error_if_failure(&ret); rb_js_abi_host_js_abi_value_free(&ret.val.success); RB_GC_GUARD(rv); return val; }
Call the receiver (a JavaScript function) with ‘undefined` as its receiver context. This method is similar to JS::Object#call
, but it is used to call a function that is not a method of an object.
floor = JS.global[:Math][:floor] floor.apply(3.14) # => 3 JS.global[:Promise].new do |resolve, reject| resolve.apply(42) end.await # => 42
# File packages/gems/js/lib/js.rb, line 216 def apply(*args, &block) args = args + [block] if block ::JS.global[:Reflect].call(:apply, self, ::JS::Undefined, args.to_js) end
Await a JavaScript Promise like ‘await` in JavaScript. This method looks like a synchronous method, but it actually runs asynchronously using fibers. In other words, the next line to the `await` call at Ruby source will be executed after the promise will be resolved. However, it does not block JavaScript event loop, so the next line to the RubyVM.evalAsync` (in the case when no `await` operator before the call expression) at JavaScript source will be executed without waiting for the promise.
The below example shows how the execution order goes. It goes in the order of “step N”
# In JavaScript const response = vm.evalAsync(` puts "step 1" JS.global.fetch("https://example.com").await puts "step 3" `) // => Promise console.log("step 2") await response console.log("step 4")
The below examples show typical usage in Ruby
JS.eval("return new Promise((ok) => setTimeout(() => ok(42), 1000))").await # => 42 (after 1 second) JS.global.fetch("https://example.com").await # => [object Response] JS.eval("return 42").await # => 42 JS.eval("return new Promise((ok, err) => err(new Error())").await # => raises JS::Error
# File packages/gems/js/lib/js.rb, line 246 def await # Promise.resolve wrap a value or flattens promise-like object and its thenable chain promise = ::JS.global[:Promise].resolve(self) ::JS.promise_scheduler.await(promise) end
Call a JavaScript method specified by the name with the arguments. Returns the result of the call as a JS::Object
.
p JS.global.call(:parseInt, JS.eval("return '42'")) # => 42 JS.global[:console].call(:log, JS.eval("return '42'")) # => undefined
static VALUE _rb_js_obj_call(int argc, VALUE *argv, VALUE obj) { struct jsvalue *p = check_jsvalue(obj); if (argc == 0) { rb_raise(rb_eArgError, "no method name given"); } VALUE method = _rb_js_obj_aref(obj, argv[0]); struct jsvalue *abi_method = check_jsvalue(method); rb_js_abi_host_list_js_abi_value_t abi_args; int function_arguments_count = argc; if (!rb_block_given_p()) function_arguments_count -= 1; abi_args.ptr = ALLOCA_N(rb_js_abi_host_js_abi_value_t, function_arguments_count); abi_args.len = function_arguments_count; VALUE rv_args = rb_ary_tmp_new(function_arguments_count); for (int i = 1; i < argc; i++) { VALUE arg = _rb_js_try_convert(rb_mJS, argv[i]); if (arg == Qnil) { rb_raise(rb_eTypeError, "argument %d is not a JS::Object like object", 1 + i); } abi_args.ptr[i - 1] = borrow_js_value(check_jsvalue(arg)->abi); rb_ary_push(rv_args, arg); } if (rb_block_given_p()) { VALUE proc = rb_block_proc(); VALUE rb_proc = _rb_js_try_convert(rb_mJS, proc); abi_args.ptr[function_arguments_count - 1] = borrow_js_value(check_jsvalue(rb_proc)->abi); rb_ary_push(rv_args, rb_proc); } rb_js_abi_host_js_abi_result_t ret; rb_js_abi_host_reflect_apply(abi_method->abi, p->abi, &abi_args, &ret); raise_js_error_if_failure(&ret); VALUE result = jsvalue_s_new(ret.val.success); RB_GC_GUARD(rv_args); RB_GC_GUARD(method); return result; }
Performs “==” comparison, a.k.a the “Abstract Equality Comparison” algorithm defined in the ECMAScript. 262.ecma-international.org/11.0/#sec-abstract-equality-comparison If the given other object is not a JS::Object
, try to convert it to a JS::Object
using JS.try_convert
. If the conversion fails, returns false.
static VALUE _rb_js_obj_eql(VALUE obj, VALUE other) { other = _rb_js_try_convert(rb_mJS, other); if (other == Qnil) { return Qfalse; } struct jsvalue *lhs = check_jsvalue(obj); struct jsvalue *rhs = check_jsvalue(other); bool result = rb_js_abi_host_js_value_equal(lhs->abi, rhs->abi); return RBOOL(result); }
Returns a printable version of self
:
JS.eval("return 'str'").to_s # => "str" JS.eval("return true").to_s # => "true" JS.eval("return 1").to_s # => "1" JS.eval("return null").to_s # => "null" JS.global.to_s # => "[object global]"
JS::Object#inspect
is an alias for JS::Object#to_s
.
Provide a shorthand form for JS::Object#call
This method basically calls the JavaScript method with the same name as the Ruby method name as is using JS::Object#call
.
Exceptions are the following cases:
-
If the method name ends with a question mark (?), the question mark is removed and the method is called as a predicate method. The return value is converted to a Ruby boolean value automatically.
This shorthand is unavailable for the following cases and you need to use JS::Object#call
instead:
-
If the method name is invalid as a Ruby method name (e.g. contains a hyphen, reserved word, etc.)
-
If the method name is already defined as a Ruby method under
JS::Object
-
If the JavaScript method name ends with a question mark (?)
# File packages/gems/js/lib/js.rb, line 184 def method_missing(sym, *args, &block) sym_str = sym.to_s if sym_str.end_with?("?") # When a JS method is called with a ? suffix, it is treated as a predicate method, # and the return value is converted to a Ruby boolean value automatically. result = invoke_js_method(sym_str[0..-2].to_sym, *args, &block) # Type coerce the result to boolean type # to match the true/false determination in JavaScript's if statement. return ::JS.global.Boolean(result) == ::JS::True end invoke_js_method(sym, *args, &block) end
Create a JavaScript object with the new method
The below examples show typical usage in Ruby
JS.global[:Object].new JS.global[:Number].new(1.23) JS.global[:String].new("string") JS.global[:Array].new(1, 2, 3) JS.global[:Date].new(2020, 1, 1) JS.global[:Error].new("error message") JS.global[:URLSearchParams].new(JS.global[:location][:search]) JS.global[:Promise].new ->(resolve, reject) { resolve.call(42) }
# File packages/gems/js/lib/js.rb, line 155 def new(*args, &block) args = args + [block] if block ::JS.global[:Reflect].construct(self, args.to_js) end
Check if a JavaScript method exists
See JS::Object#method_missing
for details.
# File packages/gems/js/lib/js.rb, line 201 def respond_to_missing?(sym, include_private) sym_str = sym.to_s sym = sym_str[0..-2].to_sym if sym_str.end_with?("?") self[sym].typeof == "function" end
Performs “===” comparison, a.k.a the “Strict Equality Comparison” algorithm defined in the ECMAScript. 262.ecma-international.org/11.0/#sec-strict-equality-comparison
static VALUE _rb_js_obj_strictly_eql(VALUE obj, VALUE other) { struct jsvalue *lhs = check_jsvalue(obj); struct jsvalue *rhs = check_jsvalue(other); bool result = rb_js_abi_host_js_value_strictly_equal(lhs->abi, rhs->abi); return RBOOL(result); }
Converts self
to an Array:
JS.eval("return [1, 2, 3]").to_a.map(&:to_i) # => [1, 2, 3] JS.global[:document].querySelectorAll("p").to_a # => [[object HTMLParagraphElement], ...
# File packages/gems/js/lib/js.rb, line 164 def to_a as_array = ::JS.global[:Array].from(self) ::Array.new(as_array[:length].to_i) { as_array[_1] } end
Converts self
to a Float:
JS.eval("return 1").to_f # => 1.0 JS.eval("return 1.2").to_f # => 1.2 JS.eval("return -1.2").to_f # => -1.2 JS.eval("return '3.14'").to_f # => 3.14 JS.eval("return ''").to_f # => 0.0 JS.eval("return 'x'").to_f # => 0.0 JS.eval("return NaN").to_f # => Float::NAN JS.eval("return Infinity").to_f # => Float::INFINITY JS.eval("return -Infinity").to_f # => -Float::INFINITY
static VALUE _rb_js_obj_to_f(VALUE obj) { struct jsvalue *p = check_jsvalue(obj); rb_js_abi_host_raw_integer_t ret; VALUE result; rb_js_abi_host_js_value_to_integer(p->abi, &ret); if (ret.tag == RB_JS_ABI_HOST_RAW_INTEGER_AS_FLOAT) { result = rb_float_new(ret.val.as_float); } else { result = DBL2NUM(rb_cstr_to_dbl((const char *)ret.val.bignum.ptr, FALSE)); } rb_js_abi_host_raw_integer_free(&ret); return result; }
Converts self
to an Integer:
JS.eval("return 1").to_i # => 1 JS.eval("return -1").to_i # => -1 JS.eval("return 5.8").to_i # => 5 JS.eval("return 42n").to_i # => 42 JS.eval("return '3'").to_i # => 3 JS.eval("return ''").to_f # => 0 JS.eval("return 'x'").to_i # => 0 JS.eval("return NaN").to_i # Raises FloatDomainError JS.eval("return Infinity").to_i # Raises FloatDomainError JS.eval("return -Infinity").to_i # Raises FloatDomainError
static VALUE _rb_js_obj_to_i(VALUE obj) { struct jsvalue *p = check_jsvalue(obj); rb_js_abi_host_raw_integer_t ret; rb_js_abi_host_js_value_to_integer(p->abi, &ret); VALUE result; if (ret.tag == RB_JS_ABI_HOST_RAW_INTEGER_AS_FLOAT) { result = rb_dbl2big(ret.val.as_float); } else { result = rb_cstr2inum((const char *)ret.val.bignum.ptr, 10); } rb_js_abi_host_raw_integer_free(&ret); return result; }
Returns a printable version of self
:
JS.eval("return 'str'").to_s # => "str" JS.eval("return true").to_s # => "true" JS.eval("return 1").to_s # => "1" JS.eval("return null").to_s # => "null" JS.global.to_s # => "[object global]"
JS::Object#inspect
is an alias for JS::Object#to_s
.
static VALUE _rb_js_obj_to_s(VALUE obj) { struct jsvalue *p = check_jsvalue(obj); rb_js_abi_host_string_t ret0; rb_js_abi_host_js_value_to_string(p->abi, &ret0); return rb_utf8_str_new((const char *)ret0.ptr, ret0.len); }
Returns the result string of JavaScript ‘typeof’ operator. See also JS.is_a?
for ‘instanceof’ operator.
p JS.global.typeof # => "object" p JS.eval("return 1").typeof # => "number" p JS.eval("return 'str'").typeof # => "string" p JS.eval("return undefined").typeof # => "undefined" p JS.eval("return null").typeof # => "object"
static VALUE _rb_js_obj_typeof(VALUE obj) { struct jsvalue *p = check_jsvalue(obj); rb_js_abi_host_string_t ret0; rb_js_abi_host_js_value_typeof(p->abi, &ret0); return rb_str_new((const char *)ret0.ptr, ret0.len); }