summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ext/json/lib/json/common.rb45
-rwxr-xr-xtest/json/json_generator_test.rb21
2 files changed, 24 insertions, 42 deletions
diff --git a/ext/json/lib/json/common.rb b/ext/json/lib/json/common.rb
index c9f6d7505b..1d939b7d1a 100644
--- a/ext/json/lib/json/common.rb
+++ b/ext/json/lib/json/common.rb
@@ -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.
diff --git a/test/json/json_generator_test.rb b/test/json/json_generator_test.rb
index 64636c12c2..05006ebd05 100755
--- a/test/json/json_generator_test.rb
+++ b/test/json/json_generator_test.rb
@@ -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,