Skip to content

Commit 01c47a0

Browse files
committed
Cleanup JSON.pretty_generate
1 parent a2cd68d commit 01c47a0

File tree

2 files changed

+24
-42
lines changed

2 files changed

+24
-42
lines changed

lib/json/common.rb

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -74,15 +74,6 @@ def generator=(generator) # :nodoc:
7474
$VERBOSE = old
7575
end
7676

77-
def create_pretty_state
78-
State.new(
79-
:indent => ' ',
80-
:space => ' ',
81-
:object_nl => "\n",
82-
:array_nl => "\n"
83-
)
84-
end
85-
8677
# Returns the JSON generator module that is used by JSON.
8778
attr_reader :generator
8879

@@ -366,6 +357,14 @@ def fast_generate(obj, opts = nil)
366357
generate(obj, opts)
367358
end
368359

360+
PRETTY_GENERATE_OPTIONS = {
361+
indent: ' ',
362+
space: ' ',
363+
object_nl: "\n",
364+
array_nl: "\n",
365+
}.freeze
366+
private_constant :PRETTY_GENERATE_OPTIONS
367+
369368
# :call-seq:
370369
# JSON.pretty_generate(obj, opts = nil) -> new_string
371370
#
@@ -397,22 +396,24 @@ def fast_generate(obj, opts = nil)
397396
# }
398397
#
399398
def pretty_generate(obj, opts = nil)
400-
if State === opts
401-
state, opts = opts, nil
402-
else
403-
state = JSON.create_pretty_state
404-
end
399+
return state.generate(obj) if State === opts
400+
401+
options = PRETTY_GENERATE_OPTIONS
402+
405403
if opts
406-
if opts.respond_to? :to_hash
407-
opts = opts.to_hash
408-
elsif opts.respond_to? :to_h
409-
opts = opts.to_h
410-
else
411-
raise TypeError, "can't convert #{opts.class} into Hash"
404+
unless opts.is_a?(Hash)
405+
if opts.respond_to? :to_hash
406+
opts = opts.to_hash
407+
elsif opts.respond_to? :to_h
408+
opts = opts.to_h
409+
else
410+
raise TypeError, "can't convert #{opts.class} into Hash"
411+
end
412412
end
413-
state.configure(opts)
413+
options = options.merge(opts)
414414
end
415-
state.generate(obj)
415+
416+
State.generate(obj, options, nil)
416417
end
417418

418419
# Sets or returns default options for the JSON.unsafe_load method.

test/json/json_generator_test.rb

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -199,26 +199,7 @@ def test_falsy_state
199199
)
200200
end
201201

202-
def test_pretty_state
203-
state = JSON.create_pretty_state
204-
assert_equal({
205-
:allow_nan => false,
206-
:array_nl => "\n",
207-
:as_json => false,
208-
:ascii_only => false,
209-
:buffer_initial_length => 1024,
210-
:depth => 0,
211-
:script_safe => false,
212-
:strict => false,
213-
:indent => " ",
214-
:max_nesting => 100,
215-
:object_nl => "\n",
216-
:space => " ",
217-
:space_before => "",
218-
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
219-
end
220-
221-
def test_safe_state
202+
def test_state_defaults
222203
state = JSON::State.new
223204
assert_equal({
224205
:allow_nan => false,

0 commit comments

Comments
 (0)