Skip to content

Commit 2311232

Browse files
committed
Prevents errors that occur when calling a non-existent JavaScript property with a question mark
1 parent 73fc7da commit 2311232

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

packages/gems/js/lib/js.rb

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -173,11 +173,15 @@ 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-
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
176+
sym = sym_str[0..-2].to_sym
177+
if self[sym].typeof == "function"
178+
result = self.call(sym, *args, &block)
179+
# Type coerce the result to boolean type
180+
# to match the true/false determination in JavaScript's if statement.
181+
JS.global.Boolean(result) == JS::True
182+
else
183+
false
184+
end
181185
elsif self[sym].typeof == "function"
182186
self.call(sym, *args, &block)
183187
else

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,8 @@ def test_method_missing_with_?
324324
return_false() { return false; },
325325
return_object() { return {}; },
326326
return_null() { return null; },
327-
return_empty_string() { return ''; }
327+
return_empty_string() { return ''; },
328+
return_number: 42
328329
};
329330
JS
330331

@@ -342,6 +343,12 @@ def test_method_missing_with_?
342343
# Return Ruby false when the return value is JavaScript false
343344
assert_false object.return_null?
344345
assert_false object.return_empty_string?
346+
347+
# Return false when the property is not a function
348+
assert_false object.return_number?
349+
350+
# Return false when function is not defined
351+
assert_false object.undefined?
345352
end
346353

347354
def test_respond_to_missing?

0 commit comments

Comments
 (0)