Skip to content

Commit 84dfd76

Browse files
Accept block in JS::Object.new
This change allows to pass a block to `JS::Object.new` method. The block will be converted to a function and passed as the last argument to the constructor. This idea was originally proposed by @ledsun in #393
1 parent afcb09f commit 84dfd76

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

packages/gems/js/lib/js.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,10 @@ class JS::Object
137137
# JS.global[:Date].new(2020, 1, 1)
138138
# JS.global[:Error].new("error message")
139139
# JS.global[:URLSearchParams].new(JS.global[:location][:search])
140+
# JS.global[:Promise].new ->(resolve, reject) { resolve.call(42) }
140141
#
141-
def new(*args)
142+
def new(*args, &block)
143+
args = args + [block] if block
142144
JS.global[:Reflect].construct(self, args.to_js)
143145
end
144146

packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,27 @@ class CustomClass {
245245
assert_equal "hello", JS.global[:CustomClass].new(js_object)[:option1].to_s
246246
end
247247

248+
def test_new_with_block
249+
ctor = JS.eval <<~JS
250+
return function (a, b, c) {
251+
this.ret = c(a, b);
252+
}
253+
JS
254+
new_obj = ctor.new(1, 2) { |a, b| a.to_i + b.to_i }
255+
assert_equal 3, new_obj[:ret].to_i
256+
257+
promise = JS.global[:Promise].new do |resolve, reject|
258+
resolve.apply 42
259+
end
260+
value = promise.await
261+
assert_equal 42, value.to_i
262+
263+
promise = JS.global[:Promise].new do |resolve, reject|
264+
JS.global.queueMicrotask(resolve)
265+
end
266+
promise.await
267+
end
268+
248269
def test_to_a
249270
assert_equal [1, 2, 3], JS.eval("return [1, 2, 3];").to_a.map(&:to_i)
250271
assert_equal %w[f o o], JS.eval("return 'foo';").to_a.map(&:to_s)

0 commit comments

Comments
 (0)