From 1f8fe28f09dbde285db276fb9c73afd14869f74c Mon Sep 17 00:00:00 2001 From: ledsun Date: Mon, 24 Jul 2023 08:58:51 +0900 Subject: [PATCH] Add JS::True and JS::False To treat the return value of a JavaScript function as a condition of a Ruby if expression, do the following if searchParams.has('phrase') == JS::True`. --- ext/js/lib/js.rb | 24 +++++++++++++++++++ .../ruby-wasm-wasi/test/unit/test_js.rb | 7 ++++++ 2 files changed, 31 insertions(+) diff --git a/ext/js/lib/js.rb b/ext/js/lib/js.rb index 44fca9a0e..a8fc29f72 100644 --- a/ext/js/lib/js.rb +++ b/ext/js/lib/js.rb @@ -41,6 +41,30 @@ module JS Undefined = JS.eval("return undefined") Null = JS.eval("return null") + # A boolean value in JavaScript is always a JS::Object instance from Ruby's point of view. + # If we use the boolean value returned by a JavaScript function as the condition for an if expression in Ruby, + # the if expression will always be true. + # + # == Bad Example + # + # searchParams = JS.global[:URLSearchParams].new(JS.global[:location][:search]) + # if searchParams.has('phrase') + # # Always pass through here. + # ... + # else + # ... + # end + # + # Therefore, the JS::True constant is used to determine if the JavaScript function return value is true or false. + # + # == Good Example + # + # if searchParams.has('phrase') == JS::True + # ... + # end + True = JS.eval("return true;") + False = JS.eval("return false;") + class PromiseScheduler def initialize(loop) @loop = loop diff --git a/packages/npm-packages/ruby-wasm-wasi/test/unit/test_js.rb b/packages/npm-packages/ruby-wasm-wasi/test/unit/test_js.rb index e1d35adfb..a317719b5 100644 --- a/packages/npm-packages/ruby-wasm-wasi/test/unit/test_js.rb +++ b/packages/npm-packages/ruby-wasm-wasi/test/unit/test_js.rb @@ -27,4 +27,11 @@ def test_eval def test_try_convert assert_nil JS.try_convert(Object.new) end + + def test_constasts + assert_equal 'null', JS::Null.to_s + assert_equal 'undefined', JS::Undefined.to_s + assert_equal 'true', JS::True.to_s + assert_equal 'false', JS::False.to_s + end end