Skip to content

Instantly share code, notes, and snippets.

@dwhelan
Created December 22, 2015 15:36
Show Gist options
  • Save dwhelan/b56d8bd2b857a8f120f8 to your computer and use it in GitHub Desktop.
Save dwhelan/b56d8bd2b857a8f120f8 to your computer and use it in GitHub Desktop.
Code commenter
class Commenter
def comment(source)
output = []
Open3.popen3(ENV, 'irb', '-f', '--noprompt', '--noverbose') do |stdin, stdout, stderr, wait_thr|
source.each do |line|
if empty_line?(line)
output << line
else
stdin.puts line
output << add_output_to_line(line, stdout.readline)
end
end
stdin.close
end
output
end
def empty_line?(line)
line =~ /^\s*($|#)/
end
def add_output_to_line(line, output)
match = line.match(/^[\t ]*([^#"'\r\n]("(\\"|[^"])*"|'(\\'|[^'])*'|[^#\n\r])*)(#\s*=>([^#\r\n]*))?/)
if match && match[5]
"#{line[0..match.begin(5)]} => #{output}"
else
line
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment