Skip to content

Commit 9ba83fe

Browse files
ledsunkateinoigakukun
authored andcommitted
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`.
1 parent 96447f8 commit 9ba83fe

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

ext/js/lib/js.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,30 @@ module JS
4141
Undefined = JS.eval("return undefined")
4242
Null = JS.eval("return null")
4343

44+
# A boolean value in JavaScript is always a JS::Object instance from Ruby's point of view.
45+
# If we use the boolean value returned by a JavaScript function as the condition for an if expression in Ruby,
46+
# the if expression will always be true.
47+
#
48+
# == Bad Example
49+
#
50+
# searchParams = JS.global[:URLSearchParams].new(JS.global[:location][:search])
51+
# if searchParams.has('phrase')
52+
# # Always pass through here.
53+
# ...
54+
# else
55+
# ...
56+
# end
57+
#
58+
# Therefore, the JS::True constant is used to determine if the JavaScript function return value is true or false.
59+
#
60+
# == Good Example
61+
#
62+
# if searchParams.has('phrase') == JS::True
63+
# ...
64+
# end
65+
True = JS.eval("return true;")
66+
False = JS.eval("return false;")
67+
4468
class PromiseScheduler
4569
def initialize(loop)
4670
@loop = loop

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,11 @@ def test_eval
2727
def test_try_convert
2828
assert_nil JS.try_convert(Object.new)
2929
end
30+
31+
def test_constasts
32+
assert_equal 'null', JS::Null.to_s
33+
assert_equal 'undefined', JS::Undefined.to_s
34+
assert_equal 'true', JS::True.to_s
35+
assert_equal 'false', JS::False.to_s
36+
end
3037
end

0 commit comments

Comments
 (0)