From 936f280f9f4f06c84c9d3eb95c1a5e36fe28039e Mon Sep 17 00:00:00 2001 From: Takashi Kokubun Date: Fri, 1 Dec 2023 09:53:44 -0800 Subject: [PATCH] Overload kwargs in JSON.dump --- lib/json/common.rb | 11 ++++++++--- tests/json_generator_test.rb | 4 ++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/json/common.rb b/lib/json/common.rb index f51f02d4d..5ba2aade0 100644 --- a/lib/json/common.rb +++ b/lib/json/common.rb @@ -615,13 +615,17 @@ def dump(obj, anIO = nil, limit = nil, kwargs = nil) if anIO and limit.nil? anIO = anIO.to_io if anIO.respond_to?(:to_io) unless anIO.respond_to?(:write) - limit = anIO + if kwargs.nil? and anIO.is_a?(Hash) + kwargs = anIO + else + limit = anIO + end anIO = nil end end opts = JSON.dump_default_options opts = opts.merge(:max_nesting => limit) if limit - merge_dump_options(opts, **kwargs) if kwargs + opts = merge_dump_options(opts, **kwargs) if kwargs result = generate(obj, opts) if anIO anIO.write result @@ -641,7 +645,8 @@ def self.iconv(to, from, string) private def merge_dump_options(opts, strict: NOT_SET) - opts[:strict] = strict if NOT_SET != strict + opts = opts.merge(strict: strict) if NOT_SET != strict + opts end end diff --git a/tests/json_generator_test.rb b/tests/json_generator_test.rb index 0ce514232..09e56e53e 100755 --- a/tests/json_generator_test.rb +++ b/tests/json_generator_test.rb @@ -66,6 +66,10 @@ def test_dump_unenclosed_hash assert_equal '{"a":1,"b":2}', dump(a: 1, b: 2) end + def test_dump_strict + assert_equal '{}', dump({}, strict: true) + end + def test_generate_pretty json = pretty_generate({}) assert_equal(<<'EOT'.chomp, json)