Skip to content

Instantly share code, notes, and snippets.

@seamusabshere
Created November 4, 2009 03:58
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 seamusabshere/225762 to your computer and use it in GitHub Desktop.
Save seamusabshere/225762 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rubygems'
require 'activesupport'
class StringReplacer
NEWLINE = "AijQA6tD1wkWqgvLzXD"
START_MARKER = '# START StringReplacer %s -- DO NOT MODIFY'
END_MARKER = "# END StringReplacer %s -- DO NOT MODIFY#{NEWLINE}"
attr_accessor :path
def initialize(path)
@path = path
end
def replace!(replacement, id = 1)
new_path = "#{path}.new"
backup_path = "#{path}.bak"
current_start_marker = START_MARKER % id.to_s
current_end_marker = END_MARKER % id.to_s
replacement_with_markers = current_start_marker + NEWLINE + replacement + NEWLINE + current_end_marker
text = IO.read(path).gsub("\n", NEWLINE)
if text.include? current_start_marker
text.gsub! /#{Regexp.escape current_start_marker}.*#{Regexp.escape current_end_marker}/, replacement_with_markers
else
text << NEWLINE << replacement_with_markers
end
text.gsub! NEWLINE, "\n"
File.open(new_path, 'w') { |f| f.write text }
FileUtils.mv path, backup_path
FileUtils.mv new_path, path
end
end
r = StringReplacer.new File.expand_path("~/Desktop/foo.txt")
r.replace! "Foo Bar"
puts IO.read("~/Desktop/foo.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment