Skip to content

Instantly share code, notes, and snippets.

@tfausak
Last active May 22, 2018 13:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfausak/49fedcf394bd29536509 to your computer and use it in GitHub Desktop.
Save tfausak/49fedcf394bd29536509 to your computer and use it in GitHub Desktop.
Test Ruby code in Markdown files.
#!/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