Skip to content

Instantly share code, notes, and snippets.

@NakedMoleRatScientist
Last active December 29, 2015 05:29
Show Gist options
  • Select an option

  • Save NakedMoleRatScientist/7621844 to your computer and use it in GitHub Desktop.

Select an option

Save NakedMoleRatScientist/7621844 to your computer and use it in GitHub Desktop.
#code_block_replacer
#A Search and Replace Utilty that insert source code into your document.
class CodeBlockReplacer
def load_lines filename
lines = []
file = File.open(filename,"r")
file.each_line do |f|
lines.push(f)
end
lines
end
def build_sectors blocks, lines
sectors = []
lines.each_with_index do |l,i|
if l.match("File: ") && (blocks[0] - 2) == i
section = {
:file => load_lines(l.split(":").last.strip()),
:begin => blocks.shift(),
:end => blocks.shift()
}
sectors.push(section)
end
end
return sectors
end
def find_blocks(lines)
blocks = []
lines.each_with_index do |l,i|
if l.match("```")
blocks.push(i)
end
end
blocks
end
def insert_msg lines, sector, offset
start = sector[:begin] + 1 + offset
finish = sector[:end] + offset
sector[:file].each.with_index(start) do |m,i|
if i >= finish
lines.insert(i,"\n")
offset += 1
end
lines[i] = m
end
return lines, offset
end
def process_file input, output = input
lines = load_lines(input)
blocks = find_blocks(lines)
sectors = build_sectors(blocks,lines)
offset = 0
sectors.each do |s|
lines, offset = insert_msg(lines,s,offset)
end
result = File.open(output,"w")
lines.each do |l|
result.write(l)
end
result.close()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment