Skip to content

Commit

Permalink
support returning object as strigified JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
hmsk committed Jun 14, 2024
1 parent 0f7f436 commit ba06c7f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
13 changes: 13 additions & 0 deletions ext/quickjsrb/quickjsrb.c
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ VALUE rb_module_eval_js_code(
if (JS_IsException(res)) {
rb_raise(rb_eRuntimeError, "Something happened by evaluating as JavaScript code");
result = Qnil;
} else if (JS_IsObject(res)) {
JSValue global = JS_GetGlobalObject(ctx);
JSValue jsonClass = JS_GetPropertyStr(ctx, global, "JSON");
JSValue stringifyFunc = JS_GetPropertyStr(ctx, jsonClass, "stringify");
JSValue strigified = JS_Call(ctx, stringifyFunc, jsonClass, 1, &res);

const char *msg = JS_ToCString(ctx, strigified);
result = rb_str_new2(msg);

JS_FreeValue(ctx, global);
JS_FreeValue(ctx, strigified);
JS_FreeValue(ctx, stringifyFunc);
JS_FreeValue(ctx, jsonClass);
} else if (JS_VALUE_IS_NAN(res)) {
result = ID2SYM(rb_intern(nanId));
} else if (JS_IsNumber(res)) {
Expand Down
5 changes: 5 additions & 0 deletions test/quickjs_test.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require "test_helper"
require "json"

class QuickjsTest < Test::Unit::TestCase
test "VERSION" do
Expand Down Expand Up @@ -44,6 +45,10 @@ class QuickjsTest < Test::Unit::TestCase
assert_equal(::Quickjs.evalCode("const func = () => 1 == 3; func();"), false)
end

test "support returning plain object" do
assert_equal(::Quickjs.evalCode("const func = () => ({ a: '1' }); func();"), JSON.dump({ a: '1' }))
end

class QuickjsTestFeatures < Test::Unit::TestCase
test "std is disabled" do
assert_equal(::Quickjs.evalCode("typeof std === 'undefined'"), true)
Expand Down

0 comments on commit ba06c7f

Please sign in to comment.