Last active
May 22, 2018 13:12
-
-
Save tfausak/49fedcf394bd29536509 to your computer and use it in GitHub Desktop.
Test Ruby code in Markdown files.
This file contains 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
#!/usr/bin/env ruby | |
pattern = /^```(.*)/ | |
capturing = false | |
language = '' | |
lines = {} | |
File.open(ARGV.shift).each_line do |line| | |
match = pattern.match(line) | |
if match | |
unless capturing | |
language = match[1].downcase.strip | |
lines[language] ||= [] | |
end | |
capturing = !capturing | |
else | |
lines[language] << line if capturing | |
end | |
end | |
pattern = /^#( =>)? (.*)/ | |
buffer = [] | |
lines.fetch('ruby').each do |line| | |
match = pattern.match(line) | |
if match | |
code = buffer.join | |
expected = match[2] | |
if match[1] | |
actual = eval(code).inspect | |
else | |
begin | |
eval(code) | |
rescue => error | |
actual = "#{error.class}: #{error.message}" | |
end | |
end | |
unless actual == expected | |
puts 'FAILURE' | |
puts "Expected: #{expected}" | |
puts "Actual: #{actual}" | |
puts "Code: #{code}" | |
puts | |
end | |
buffer = [] | |
else | |
buffer << line | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment