class RecursiveReplace
Constants
- INDENTATION
Public Class Methods
files_inside(path)
click to toggle source
# File lib/recursive_replace.rb, line 48 def self.files_inside(path) # get the working directory to start in path.nil? ? Dir.glob(File.join("**", "*")) : Dir.glob(File.join(path, "**", "*")) end
prepare(string)
click to toggle source
# File lib/recursive_replace.rb, line 52 def self.prepare(string) # prepare string for use in replacement: escape, etc. prepared = Regexp.escape(string) prepared = prepared.sub("/", "\\/") # prepend escape characted forward slash with since it will be be used with sed in shell #print "Postprepare #{string} => #{prepared}" return prepared end
print_path(path)
click to toggle source
# File lib/recursive_replace.rb, line 44 def self.print_path(path) path end
print_path_with_indent(path)
click to toggle source
# File lib/recursive_replace.rb, line 36 def self.print_path_with_indent(path) # print pretty path indent = String.new path.split(File::SEPARATOR).each do indent << RecursiveReplace::INDENTATION unless File.dirname(path) == "." end return File.directory?(path) ? path : indent + File.basename(path) end
replace(original, replacement, options = {})
click to toggle source
# File lib/recursive_replace.rb, line 6 def self.replace(original, replacement, options = {}) # replace text in either a directory(recursively) or single file #exec("find ./ -type f | xargs sed -i 's/#{@string1}/#{@string2}/g'") #puts files.inspect if options[:path].nil? || File.directory?(options[:path]) # recursively inside directory for file in files_inside(options[:path]) options[:path] = file replace_in_file(original, replacement, options) unless File.directory?(file) end else # single file replace_in_file(original, replacement, options) end end
replace_in_file(original, replacement, options = {})
click to toggle source
# File lib/recursive_replace.rb, line 20 def self.replace_in_file(original, replacement, options = {}) # do the actual replacing in a single file raise ScriptError, "options[:path] not defined" if options[:path].nil? raise LoadError, "#{options[:path]} not found" unless File.exists?(options[:path]) raise LoadError, "#{options[:path]} is a directory" if File.directory?(options[:path]) # Set Defaults options[:verbose] = false if options[:verbose].nil? original = prepare(original) # escape any special characters replacement = prepare(replacement) results = system("sed -i 's/#{original}/#{replacement}/g' #{options[:path]}") puts "success".green + "\t" + INDENTATION + print_path(options[:path]) if !File.directory?(options[:path]) && options[:verbose] #puts results.inspect end