class RSpec::JsonHelpers::Formatter

@api private

Constants

WRONG_TYPE

Public Instance Methods

format(json) click to toggle source

@param [String<JSON>] json @return [String<JSON>] @raise ArgumentError Raises `ArgumentError` when the given

json value is not a string, or when when there is an error
parsring string as JSON.
# File lib/rspec/json_helpers/formatter.rb, line 17
def format(json)
  dump_json(deep_sort(parse_json(json)))
rescue JSON::ParserError => e
  raise ArgumentError, 'Expected a string containing valid ' \
    "JSON; got #{e.class.name}: #{e.message}"
end

Private Instance Methods

deep_sort(obj) click to toggle source
# File lib/rspec/json_helpers/formatter.rb, line 38
def deep_sort(obj)
  case obj
  when Hash
    obj.keys.sort.each_with_object({}) do |key, hash|
      hash[key] = deep_sort(obj[key])
    end
  when Array
    obj.map { |value| deep_sort(value) }
  when String, Numeric, true, false, nil
    obj
  end
end
dump_json(value) click to toggle source
# File lib/rspec/json_helpers/formatter.rb, line 34
def dump_json(value)
  JSON.pretty_generate(value, indent: '  ')
end
parse_json(json) click to toggle source
# File lib/rspec/json_helpers/formatter.rb, line 26
def parse_json(json)
  if json.is_a?(String)
    JSON.parse(json)
  else
    raise ArgumentError, Kernel.format(WRONG_TYPE, type: json.class.name)
  end
end