Class: File
- Inherits:
-
Object
- Object
- File
- Defined in:
- lib/File/extname.rb,
lib/File/self.gsubX.rb,
lib/File/basename_without_extname.rb
Overview
Changes:
-
/File.gsubX/File/self.gsubX/.
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.gsub!(filename, replacement_pattern, replacement_text, selection_pattern = nil) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/File/self.gsubX.rb', line 17 def self.gsub!(filename, replacement_pattern, replacement_text, selection_pattern = nil) replacement_pattern = ( case replacement_pattern when String; Regexp.new(Regexp.escape(replacement_pattern)) when Regexp; replacement_pattern else; raise end ) selection_pattern = replacement_pattern unless selection_pattern selection_pattern = ( case selection_pattern when String; Regexp.new(Regexp.escape(selection_pattern)) when Regexp; selection_pattern else; raise end ) file_handle = self.open(filename, 'r') tmp_file_handle = self.new(filename + '.tmp', 'w') modified = false file_handle.each do |line| if line =~ Regexp.new(selection_pattern) tmp_file_handle.print line.gsub(Regexp.new(replacement_pattern), replacement_text) modified = true else tmp_file_handle.print line end end file_handle.close tmp_file_handle.close if modified self.delete(filename) self.rename(filename + '.tmp', filename) else self.delete(filename + '.tmp') end end |