Skip to content

Commit 94ce022

Browse files
Merge pull request #443 from ledsun/question_method_judgement_condition
Matches the return value of a JavaScript method with ? with a true/false decision in a JavaScript if statement
2 parents 2008223 + 3c1bb02 commit 94ce022

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

packages/gems/js/lib/js.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,11 @@ def method_missing(sym, *args, &block)
173173
if sym_str.end_with?("?")
174174
# When a JS method is called with a ? suffix, it is treated as a predicate method,
175175
# and the return value is converted to a Ruby boolean value automatically.
176-
self.call(sym_str[0..-2].to_sym, *args, &block) == JS::True
176+
result = self.call(sym_str[0..-2].to_sym, *args, &block)
177+
178+
# Type coerce the result to boolean type
179+
# to match the true/false determination in JavaScript's if statement.
180+
JS.global.Boolean(result) == JS::True
177181
elsif self[sym].typeof == "function"
178182
self.call(sym, *args, &block)
179183
else

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

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,9 @@ def test_method_missing_with_?
322322
return {
323323
return_true() { return true; },
324324
return_false() { return false; },
325-
return_object() { return {}; }
325+
return_object() { return {}; },
326+
return_null() { return null; },
327+
return_empty_string() { return ''; }
326328
};
327329
JS
328330

@@ -334,8 +336,12 @@ def test_method_missing_with_?
334336
assert_true object.return_true?
335337
assert_false object.return_false?
336338

337-
# Return Ruby false when the return value is not JS::True
338-
assert_false object.return_object?
339+
# Return Ruby true when the return value is JavaScript true
340+
assert_true object.return_object?
341+
342+
# Return Ruby false when the return value is JavaScript false
343+
assert_false object.return_null?
344+
assert_false object.return_empty_string?
339345
end
340346

341347
def test_respond_to_missing?

0 commit comments

Comments
 (0)