Skip to content

Instantly share code, notes, and snippets.

@elcgist
Created April 6, 2009 18:19
Show Gist options
  • Save elcgist/90865 to your computer and use it in GitHub Desktop.
Save elcgist/90865 to your computer and use it in GitHub Desktop.
class File
def replace(pattern, string)
full_path = File.expand_path path
return unless File.file?(full_path)
reopen(full_path, 'r')
lines = readlines
changes = false
lines.each_with_index do |line, index|
if line.gsub!(pattern, string)
changes = true
$stdout << "#{full_path}:#{index} #{line}"
end
end
if changes
reopen(full_path, 'w')
lines.each do |line|
write(line)
end
close
end
end
def replace_token(token, string)
replace(/\b#{token}\b/, string)
end
end
module Refactor
class Base
def self.paths(*args)
@@paths = args
end
def self.replace(args={})
@@subs = args
end
def execute
if @@paths.nil?
raise "No paths specified for refactor #{self.class}."
end
if @@subs.nil?
raise "No replacements for refactor #{self.class}."
end
@@paths.each do |glob|
Dir[glob].each do |filename|
next if File.directory?(filename)
file = File.open(filename)
@@subs.each do |token, string|
file.replace_token token, string
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment