Class: JS::Object

Inherits:
BasicObject
Defined in:
lib/js.rb,
ext/js/js-core.c,
ext/js/js-core.c

Overview

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("  return {\n    method1: function(str, num) {\n      // str is a JavaScript string and num is a JavaScript number.\n      return str.length + num\n   },\n    method2: function(rbObject) {\n      // Call String#upcase method for the given Ruby object (RbValue).\n      return rbObject.call(\"upcase\").toString();\n    }\n  }\n")
# 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)

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object

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 (?)



184
185
186
187
188
189
190
191
192
193
194
195
196
# File '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

Class Method Details

.JS::Object.wrap(obj) ⇒ JS::Object

Returns obj wrapped by JS class RbValue.

Returns:



453
454
455
456
457
458
459
460
461
462
# File 'ext/js/js-core.c', line 453

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
}

Instance Method Details

#==(other) ⇒ Boolean #eql?(other) ⇒ Boolean

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.

Overloads:

  • #==(other) ⇒ Boolean

    Returns:

    • (Boolean)
  • #eql?(other) ⇒ Boolean

    Returns:

    • (Boolean)


259
260
261
262
263
264
265
266
267
268
# File 'ext/js/js-core.c', line 259

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);
}

#[](prop) ⇒ JS::Object

Returns the value of the property:

JS.global[:Object]
JS.global[:console][:log]

Returns:



193
194
195
196
197
198
199
200
201
202
# File 'ext/js/js-core.c', line 193

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);
}

#[]=(prop) ⇒ JS::Object

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"

Returns:



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'ext/js/js-core.c', line 213

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;
}

#apply(*args, &block) ⇒ Object

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


216
217
218
219
# File '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

#awaitObject

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


246
247
248
249
250
# File '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(name, *args) ⇒ JS::Object

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

Returns:



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'ext/js/js-core.c', line 288

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;
}

#==(other) ⇒ Boolean #eql?(other) ⇒ Boolean

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.

Overloads:

  • #==(other) ⇒ Boolean

    Returns:

    • (Boolean)
  • #eql?(other) ⇒ Boolean

    Returns:

    • (Boolean)


259
260
261
262
263
264
265
266
267
268
# File 'ext/js/js-core.c', line 259

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);
}

#hashObject

:nodoc: all



273
274
275
276
277
# File 'ext/js/js-core.c', line 273

static VALUE _rb_js_obj_hash(VALUE obj) {
  // TODO(katei): Track the JS object id in JS side as Pyodide and Swift
  // JavaScriptKit do.
  return Qnil;
}

#new(*args, &block) ⇒ Object

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) }


155
156
157
158
# File 'lib/js.rb', line 155

def new(*args, &block)
  args = args + [block] if block
  ::JS.global[:Reflect].construct(self, args.to_js)
end

#respond_to_missing?(sym, include_private) ⇒ Boolean

Check if a JavaScript method exists

See JS::Object#method_missing for details.

Returns:

  • (Boolean)


201
202
203
204
205
# File '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

#strictly_eql?(other) ⇒ Boolean

Performs “===” comparison, a.k.a the “Strict Equality Comparison” algorithm defined in the ECMAScript. 262.ecma-international.org/11.0/#sec-strict-equality-comparison

Returns:

  • (Boolean)


241
242
243
244
245
246
# File 'ext/js/js-core.c', line 241

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);
}

#to_aObject

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], ...


164
165
166
167
# File '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

#to_fFloat

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

Returns:



418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'ext/js/js-core.c', line 418

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;
}

#to_iInteger

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

Returns:



388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'ext/js/js-core.c', line 388

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;
}

#to_sString Also known as: inspect

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.

Returns:



365
366
367
368
369
370
# File 'ext/js/js-core.c', line 365

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);
}

#typeofString

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"

Returns:



345
346
347
348
349
350
# File 'ext/js/js-core.c', line 345

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);
}