[ruby/json] Cleanup JSON.pretty_generate
https://github.com/ruby/json/commit/01c47a0555
This commit is contained in:
parent
2b9a9300ac
commit
26e55562ce
Notes:
git
2025-03-28 03:45:14 +00:00
@ -74,15 +74,6 @@ module JSON
|
||||
$VERBOSE = old
|
||||
end
|
||||
|
||||
def create_pretty_state
|
||||
State.new(
|
||||
:indent => ' ',
|
||||
:space => ' ',
|
||||
:object_nl => "\n",
|
||||
:array_nl => "\n"
|
||||
)
|
||||
end
|
||||
|
||||
# Returns the JSON generator module that is used by JSON.
|
||||
attr_reader :generator
|
||||
|
||||
@ -366,6 +357,14 @@ module JSON
|
||||
generate(obj, opts)
|
||||
end
|
||||
|
||||
PRETTY_GENERATE_OPTIONS = {
|
||||
indent: ' ',
|
||||
space: ' ',
|
||||
object_nl: "\n",
|
||||
array_nl: "\n",
|
||||
}.freeze
|
||||
private_constant :PRETTY_GENERATE_OPTIONS
|
||||
|
||||
# :call-seq:
|
||||
# JSON.pretty_generate(obj, opts = nil) -> new_string
|
||||
#
|
||||
@ -397,22 +396,24 @@ module JSON
|
||||
# }
|
||||
#
|
||||
def pretty_generate(obj, opts = nil)
|
||||
if State === opts
|
||||
state, opts = opts, nil
|
||||
else
|
||||
state = JSON.create_pretty_state
|
||||
end
|
||||
return state.generate(obj) if State === opts
|
||||
|
||||
options = PRETTY_GENERATE_OPTIONS
|
||||
|
||||
if opts
|
||||
if opts.respond_to? :to_hash
|
||||
opts = opts.to_hash
|
||||
elsif opts.respond_to? :to_h
|
||||
opts = opts.to_h
|
||||
else
|
||||
raise TypeError, "can't convert #{opts.class} into Hash"
|
||||
unless opts.is_a?(Hash)
|
||||
if opts.respond_to? :to_hash
|
||||
opts = opts.to_hash
|
||||
elsif opts.respond_to? :to_h
|
||||
opts = opts.to_h
|
||||
else
|
||||
raise TypeError, "can't convert #{opts.class} into Hash"
|
||||
end
|
||||
end
|
||||
state.configure(opts)
|
||||
options = options.merge(opts)
|
||||
end
|
||||
state.generate(obj)
|
||||
|
||||
State.generate(obj, options, nil)
|
||||
end
|
||||
|
||||
# Sets or returns default options for the JSON.unsafe_load method.
|
||||
|
@ -199,26 +199,7 @@ class JSONGeneratorTest < Test::Unit::TestCase
|
||||
)
|
||||
end
|
||||
|
||||
def test_pretty_state
|
||||
state = JSON.create_pretty_state
|
||||
assert_equal({
|
||||
:allow_nan => false,
|
||||
:array_nl => "\n",
|
||||
:as_json => false,
|
||||
:ascii_only => false,
|
||||
:buffer_initial_length => 1024,
|
||||
:depth => 0,
|
||||
:script_safe => false,
|
||||
:strict => false,
|
||||
:indent => " ",
|
||||
:max_nesting => 100,
|
||||
:object_nl => "\n",
|
||||
:space => " ",
|
||||
:space_before => "",
|
||||
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
|
||||
end
|
||||
|
||||
def test_safe_state
|
||||
def test_state_defaults
|
||||
state = JSON::State.new
|
||||
assert_equal({
|
||||
:allow_nan => false,
|
||||
|
Loading…
x
Reference in New Issue
Block a user