Skip to content

Commit 560b526

Browse files
Update HashFormatter
1 parent 66f3cb0 commit 560b526

File tree

2 files changed

+15
-17
lines changed

2 files changed

+15
-17
lines changed

lib/amazing_print/formatters/hash_formatter.rb

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def left_width(keys)
8585
end
8686

8787
def max_key_width(keys)
88-
keys.map { |key, _value| colorless_size(key) }.max || 0
88+
keys.map { |key, _value| colorless_size(key.to_s) }.max || 0
8989
end
9090

9191
def printable_keys
@@ -95,7 +95,10 @@ def printable_keys
9595

9696
keys.map! do |key|
9797
plain_single_line do
98-
[inspector.awesome(key), hash[key]]
98+
[
99+
json_format? ? key : inspector.awesome(key),
100+
hash[key]
101+
]
99102
end
100103
end
101104
end
@@ -108,20 +111,12 @@ def symbol?(key)
108111
key[0] == ':'
109112
end
110113

111-
def json_syntax(key, value, width)
112-
formatted_key = if symbol?(key)
113-
# Symbols should have a colon we need to remove
114-
# Strings should have surrounding double quotes we need to remove
115-
# symbol?(key) ? key[1..-1] : key[1..-2]
116-
key[1..-1].to_json
117-
elsif string?(key)
118-
key
119-
elsif key.respond_to?(:to_json)
120-
key.to_json
121-
else
122-
key
123-
end
114+
def json_format?
115+
options[:hash_format] == :json
116+
end
124117

118+
def json_syntax(key, value, width)
119+
formatted_key = json_awesome(key, is_key: true)
125120
formatted_value = json_awesome(value)
126121

127122
"#{align(formatted_key, width)}#{colorize(': ', :hash)}#{formatted_value}"

lib/amazing_print/json_helper.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@
55
#
66
module AmazingPrint
77
module JSONHelper
8-
def json_awesome(object)
8+
def json_awesome(object, is_key: false)
99
return inspector.awesome(object) unless options[:hash_format] == :json
1010

1111
if object.nil?
1212
# Color null like we do nil
1313
colorize(object.to_json, :nilclass)
14-
elsif [Array, Float, Hash, Integer, String].include?(object.class) || !object.respond_to?(:to_json)
14+
elsif is_key && %w[BigDecimal Float Integer].include?(object.class.name)
15+
# JSON keys should be a string
16+
inspector.awesome(object.to_s)
17+
elsif %w[Array BigDecimal Float Hash Integer String].include?(object.class.name) || !object.respond_to?(:to_json)
1518
# These objects should not be converted to strings with #to_json so we can treat them normally
1619
inspector.awesome(object)
1720
else

0 commit comments

Comments
 (0)