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

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

.wrap(wrapping) ⇒ Object



460
461
462
463
464
465
466
467
468
469
# File 'ext/js/js-core.c', line 460

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) ⇒ Object



262
263
264
265
266
267
268
269
270
271
# File 'ext/js/js-core.c', line 262

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

#[](key) ⇒ Object



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

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);
  rb_js_abi_host_string_free(&key_abi_str);
  raise_js_error_if_failure(&ret);
  return jsvalue_s_new(ret.val.success);
}

#[]=(key, val) ⇒ Object



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

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);
  rb_js_abi_host_string_free(&key_abi_str);
  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 noawait` 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(*args) ⇒ Object



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
332
333
334
# File 'ext/js/js-core.c', line 291

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

#eql?(other) ⇒ Object



262
263
264
265
266
267
268
269
270
271
# File 'ext/js/js-core.c', line 262

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



276
277
278
279
280
# File 'ext/js/js-core.c', line 276

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) ⇒ Object



244
245
246
247
248
249
# File 'ext/js/js-core.c', line 244

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_fObject



425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'ext/js/js-core.c', line 425

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_iObject



395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'ext/js/js-core.c', line 395

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_sObject Also known as: inspect



370
371
372
373
374
375
376
377
# File 'ext/js/js-core.c', line 370

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);
  VALUE to_s_str = rb_utf8_str_new((const char *)ret0.ptr, ret0.len);
  rb_js_abi_host_string_free(&ret0);
  return to_s_str;
}

#typeofObject



348
349
350
351
352
353
354
355
# File 'ext/js/js-core.c', line 348

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);
  VALUE typeof_str = rb_str_new((const char *)ret0.ptr, ret0.len);
  rb_js_abi_host_string_free(&ret0);
  return typeof_str;
}