Class: JS::Object

Inherits:
Object
  • Object
show all
Defined in:
ext/js/js-core.c,
ext/js/lib/js.rb,
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 (?)



165
166
167
168
169
170
171
172
173
174
175
176
# File 'ext/js/lib/js.rb', line 165

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.
    self.call(sym_str[0..-2].to_sym, *args, &block) == JS::True
  elsif self[sym].typeof == "function"
    self.call(sym, *args, &block)
  else
    super
  end
end

Class Method Details

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

Returns obj wrapped by JS class RbValue.

Returns:



428
429
430
431
432
# File 'ext/js/js-core.c', line 428

static VALUE _rb_js_obj_wrap(VALUE obj, VALUE wrapping) {
  rb_abi_lend_object(wrapping);
  return jsvalue_s_new(
      rb_js_abi_host_rb_object_to_js_rb_value((uint32_t)wrapping));
}

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

Overloads:

  • #==(other) ⇒ Boolean

    Returns:

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

    Returns:

    • (Boolean)


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

static VALUE _rb_js_obj_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_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:



180
181
182
183
184
185
186
187
188
189
# File 'ext/js/js-core.c', line 180

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:



200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'ext/js/js-core.c', line 200

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

#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


213
214
215
216
217
# File 'ext/js/lib/js.rb', line 213

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:



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'ext/js/js-core.c', line 264

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] = 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] = 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

Overloads:

  • #==(other) ⇒ Boolean

    Returns:

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

    Returns:

    • (Boolean)


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

static VALUE _rb_js_obj_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_equal(lhs->abi, rhs->abi);
  return RBOOL(result);
}

#hashObject

:nodoc: all



249
250
251
252
253
# File 'ext/js/js-core.c', line 249

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


137
138
139
# File 'ext/js/lib/js.rb', line 137

def new(*args)
  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)


181
182
183
184
185
186
# File 'ext/js/lib/js.rb', line 181

def respond_to_missing?(sym, include_private)
  return true if super
  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)


223
224
225
226
227
228
# File 'ext/js/js-core.c', line 223

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


145
146
147
148
# File 'ext/js/lib/js.rb', line 145

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:



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

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_F64) {
    result = rb_float_new(ret.val.f64);
  } else {
    result = DBL2NUM(rb_cstr_to_dbl(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:



363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'ext/js/js-core.c', line 363

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_F64) {
    result = rb_dbl2big(ret.val.f64);
  } else {
    result = rb_cstr2inum(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:



340
341
342
343
344
345
# File 'ext/js/js-core.c', line 340

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



320
321
322
323
324
325
# File 'ext/js/js-core.c', line 320

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(ret0.ptr, ret0.len);
}