Skip to content

Commit

Permalink
parse JSON instead of returning stringified
Browse files Browse the repository at this point in the history
  • Loading branch information
hmsk committed Jun 15, 2024
1 parent 2597a03 commit de5d624
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 3 deletions.
2 changes: 2 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion ext/quickjsrb/quickjsrb.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions lib/quickjs.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# frozen_string_literal: true

require "json"
require_relative "quickjs/version"
require_relative "quickjs/quickjsrb"

Expand Down
1 change: 1 addition & 0 deletions quickjs.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -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|
Expand Down
6 changes: 4 additions & 2 deletions test/quickjs_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit de5d624

Please sign in to comment.