From de5d624b56ec8fd9d69458362bde76fdf6d36b0a Mon Sep 17 00:00:00 2001 From: hmsk Date: Fri, 14 Jun 2024 21:13:54 -0700 Subject: [PATCH] parse JSON instead of returning stringified --- Gemfile.lock | 2 ++ ext/quickjsrb/quickjsrb.c | 4 +++- lib/quickjs.rb | 1 + quickjs.gemspec | 1 + test/quickjs_test.rb | 6 ++++-- 5 files changed, 11 insertions(+), 3 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index 4f645b2..98c80c9 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -2,10 +2,12 @@ PATH remote: . specs: quickjs (0.1.2) + json GEM remote: https://rubygems.org/ specs: + json (2.7.2) power_assert (2.0.3) rake (13.2.1) rake-compiler (1.2.7) diff --git a/ext/quickjsrb/quickjsrb.c b/ext/quickjsrb/quickjsrb.c index 27f6bb8..7bdaff0 100644 --- a/ext/quickjsrb/quickjsrb.c +++ b/ext/quickjsrb/quickjsrb.c @@ -60,7 +60,9 @@ VALUE rb_module_eval_js_code( JSValue strigified = JS_Call(ctx, stringifyFunc, jsonClass, 1, &res); const char *msg = JS_ToCString(ctx, strigified); - result = rb_str_new2(msg); + VALUE rbString = rb_str_new2(msg); + VALUE rb_cJson = rb_const_get(rb_cClass, rb_intern("JSON")); + result = rb_funcall(rb_cJson, rb_intern("parse"), 1, rbString); JS_FreeValue(ctx, global); JS_FreeValue(ctx, strigified); diff --git a/lib/quickjs.rb b/lib/quickjs.rb index e1ee1a1..257e407 100644 --- a/lib/quickjs.rb +++ b/lib/quickjs.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require "json" require_relative "quickjs/version" require_relative "quickjs/quickjsrb" diff --git a/quickjs.gemspec b/quickjs.gemspec index eb29563..886a52f 100644 --- a/quickjs.gemspec +++ b/quickjs.gemspec @@ -18,6 +18,7 @@ Gem::Specification.new do |spec| spec.metadata['source_code_uri'] = spec.homepage spec.metadata['changelog_uri'] = 'https://github.com/hmsk/quickjs.rb/blob/main/CHANGELOG.md' + spec.add_runtime_dependency 'json' gemspec = File.basename(__FILE__) spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| ls.readlines("\x0", chomp: true).reject do |f| diff --git a/test/quickjs_test.rb b/test/quickjs_test.rb index c4e2612..7ec83b4 100644 --- a/test/quickjs_test.rb +++ b/test/quickjs_test.rb @@ -45,8 +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' })) + test "support returning plain object/array" do + assert_equal(::Quickjs.evalCode("const func = () => ({ a: '1', b: 1 }); func();"), { 'a' => '1', 'b' => 1 }) + assert_equal(::Quickjs.evalCode("const func = () => ({ funcCantRemain: () => {} }); func();"), {}) + assert_equal(::Quickjs.evalCode("[1,2,3]"), [1,2,3]) end class QuickjsTestFeatures < Test::Unit::TestCase