Skip to content

Instantly share code, notes, and snippets.

@brandonmwest
Last active December 21, 2015 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonmwest/6335429 to your computer and use it in GitHub Desktop.
Save brandonmwest/6335429 to your computer and use it in GitHub Desktop.
ruby script for pretty printing JSON and XML inside of octopress {% codeblock %} tags
require 'rubygems'
require 'json'
require 'nokogiri'
require 'nokogiri-pretty'
markdown_files = File.join("/docs/source", "**", "*.md")
Dir.glob markdown_files do |markdown_file|
next if markdown_file == '.' or markdown_file == '..'
path = markdown_file
file = File.open(path)
contents = file.read
#Pretty print the JSON
contents.gsub!(/({%\s?codeblock lang:javascript\s?%})(.*?)({\%\s?endcodeblock\s?%})/m) do |match|
begin
json = JSON.parse($2)
rescue
puts "invalid JSON or non-JSON javascript block in #{markdown_file}: #{$2})"
next
end
puts $1 + JSON.pretty_generate(json) + $3
$1 + "\n" + JSON.pretty_generate(json) + "\n" + $3
end
#Pretty print the XML
contents.gsub!(/({%\s?codeblock lang:xml\s?%})(.*?)({\%\s?endcodeblock\s?%})/m) do |match|
begin
xml = Nokogiri.XML($2)
rescue
puts "invalid XML block in #{markdown_file}: #{$2})"
next
end
puts $1 + xml.human + $3
$1 + "\n" + xml.human + "\n" + $3
end
output_path = 'output/' + File.basename(file)
file = File.new(output_path,"w")
file.write(contents)
file.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment