Skip to content

Commit

Permalink
Merge pull request #556 from k0kubun/dump-kwargs
Browse files Browse the repository at this point in the history
Overload kwargs in JSON.dump
  • Loading branch information
hsbt committed Dec 4, 2023
2 parents 691d6b1 + 936f280 commit 3a5f2d2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
11 changes: 8 additions & 3 deletions lib/json/common.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
4 changes: 4 additions & 0 deletions tests/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 3a5f2d2

Please sign in to comment.