Skip to content

Commit

Permalink
support returning undefined with identifying by symbol
Browse files Browse the repository at this point in the history
  • Loading branch information
hmsk committed Jun 12, 2024
1 parent 29acdc3 commit fad763a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
9 changes: 8 additions & 1 deletion ext/quickjsrb/quickjsrb.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#include "quickjsrb.h"

VALUE rb_mQuickjs;
VALUE rb_mQuickjsValue;
const char *undefinedId = "undefined";

VALUE rb_module_eval_js_code(VALUE klass, VALUE r_code)
{
Expand Down Expand Up @@ -37,7 +39,9 @@ VALUE rb_module_eval_js_code(VALUE klass, VALUE r_code)
result = rb_str_new2(msg);
} else if (JS_IsBool(res)) {
result = JS_ToBool(ctx, res) > 0 ? Qtrue : Qfalse;
} else if (JS_IsNull(res) || JS_IsUndefined(res)) {
} else if (JS_IsUndefined(res)) {
result = ID2SYM(rb_intern(undefinedId));
} else if (JS_IsNull(res)) {
result = Qnil;
} else {
result = Qnil;
Expand All @@ -54,4 +58,7 @@ Init_quickjsrb(void)
{
rb_mQuickjs = rb_define_module("Quickjs");
rb_define_module_function(rb_mQuickjs, "evalCode", rb_module_eval_js_code, 1);

VALUE valueClass = rb_define_class_under(rb_mQuickjs, "Value", rb_cObject);
rb_define_const(valueClass, "UNDEFINED", ID2SYM(rb_intern(undefinedId)));
}
5 changes: 5 additions & 0 deletions test/quickjs_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ class QuickjsTest < Test::Unit::TestCase
assert_equal(::Quickjs.evalCode("const func = () => null; func();"), nil)
end

test "support returning undefined" do
assert_equal(::Quickjs.evalCode("undefined"), Quickjs::Value::UNDEFINED)
assert_equal(::Quickjs.evalCode("const obj = {}; obj.key;"), Quickjs::Value::UNDEFINED)
end

test "support returning string" do
assert_equal(::Quickjs.evalCode("'1'"), "1")
assert_equal(::Quickjs.evalCode("const func = () => 'hello'; func();"), "hello")
Expand Down

0 comments on commit fad763a

Please sign in to comment.