Skip to content

Add JS::True and JS::False #248

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions ext/js/lib/js.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions packages/npm-packages/ruby-wasm-wasi/test/unit/test_js.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I use JS::Object with assert_equal as the argument, I get the following error:

JS::Error: TypeError: Cannot read properties of null (reading 'encoding')

To avoid the error, I compare with a string.

end
end