Skip to content

Commit

Permalink
Accept block in JS::Object.new
Browse files Browse the repository at this point in the history
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
  • Loading branch information
kateinoigakukun committed Mar 16, 2024
1 parent afcb09f commit 84dfd76
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/gems/js/lib/js.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,10 @@ class JS::Object
# 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) }
#
def new(*args)
def new(*args, &block)
args = args + [block] if block
JS.global[:Reflect].construct(self, args.to_js)
end

Expand Down
21 changes: 21 additions & 0 deletions packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,27 @@ class CustomClass {
assert_equal "hello", JS.global[:CustomClass].new(js_object)[:option1].to_s
end

def test_new_with_block
ctor = JS.eval <<~JS
return function (a, b, c) {
this.ret = c(a, b);
}
JS
new_obj = ctor.new(1, 2) { |a, b| a.to_i + b.to_i }
assert_equal 3, new_obj[:ret].to_i

promise = JS.global[:Promise].new do |resolve, reject|
resolve.apply 42
end
value = promise.await
assert_equal 42, value.to_i

promise = JS.global[:Promise].new do |resolve, reject|
JS.global.queueMicrotask(resolve)
end
promise.await
end

def test_to_a
assert_equal [1, 2, 3], JS.eval("return [1, 2, 3];").to_a.map(&:to_i)
assert_equal %w[f o o], JS.eval("return 'foo';").to_a.map(&:to_s)
Expand Down

0 comments on commit 84dfd76

Please sign in to comment.