Created
October 22, 2012 14:06
-
-
Save miwest929/3931661 to your computer and use it in GitHub Desktop.
scripts that pretty-prints all JSON in api scenarios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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