Skip to content

Instantly share code, notes, and snippets.

@miwest929
Created October 22, 2012 14:06
Show Gist options
  • Select an option

  • Save miwest929/3931661 to your computer and use it in GitHub Desktop.

Select an option

Save miwest929/3931661 to your computer and use it in GitHub Desktop.
scripts that pretty-prints all JSON in api scenarios
require 'json'
module PrettyPrintJSON
CUCUMBER_JSON_DELIMETER = '"""'
def self.from_file(filename)
in_json_block = false
json_block = ""
formatted_file = ""
# r+ file access mode = read/write access, file pointer points to beginning of file.
f = File.new(filename, "r+")
f.lines.each do |line|
delimeter_indent_count = line.index(CUCUMBER_JSON_DELIMETER)
is_json_delimeter = !delimeter_indent_count.nil?
in_json_block = !in_json_block if is_json_delimeter
# inside the json block
if !is_json_delimeter && in_json_block
json_block << line
# Just exited a json block
elsif is_json_delimeter && !in_json_block
begin
parsed_hash = JSON.parse(json_block)
pretty_json = JSON.pretty_generate(parsed_hash)
pretty_json = "#{' '*delimeter_indent_count}#{pretty_json}"
pretty_json.gsub!("\n", "\n#{' '*delimeter_indent_count}")
formatted_file << pretty_json
formatted_file << "\n"
rescue JSON::ParserError
formatted_file << json_block
end
formatted_file << line
json_block = ""
else
formatted_file << line
end
end
f.rewind
f.write(formatted_file)
f.close
end
end
Dir.glob(File.join("features/api", "**", "*.feature")) do |filename|
PrettyPrintJSON.from_file(filename)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment