Class: StringReplacer
- Inherits:
-
Object
- Object
- StringReplacer
- Defined in:
- lib/string_replacer.rb
Constant Summary collapse
- NEWLINE =
"AijQA6tD1wkWqgvLzXD"
- START_MARKER =
'# START StringReplacer %s -- DO NOT MODIFY'
- END_MARKER =
"# END StringReplacer %s -- DO NOT MODIFY#{NEWLINE}"
Instance Attribute Summary collapse
-
#path ⇒ Object
Returns the value of attribute path.
Instance Method Summary collapse
-
#initialize(path) ⇒ StringReplacer
constructor
A new instance of StringReplacer.
- #replace!(string, replacement_id, after_line) ⇒ Object
Constructor Details
#initialize(path) ⇒ StringReplacer
Returns a new instance of StringReplacer.
9 10 11 |
# File 'lib/string_replacer.rb', line 9 def initialize(path) @path = path end |
Instance Attribute Details
#path ⇒ Object
Returns the value of attribute path.
8 9 10 |
# File 'lib/string_replacer.rb', line 8 def path @path end |
Instance Method Details
#replace!(string, replacement_id, after_line) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/string_replacer.rb', line 13 def replace!(string, replacement_id, after_line) replacement_id = 1 unless replacement_id.to_s.strip.length > 0 after_line = nil unless after_line.to_s.strip.length > 0 new_path = "#{path}.new" backup_path = "#{path}.bak" current_start_marker = START_MARKER % replacement_id.to_s current_end_marker = END_MARKER % replacement_id.to_s string_with_markers = current_start_marker + NEWLINE + string + NEWLINE + current_end_marker text = IO.read(path).gsub("\n", NEWLINE) if text.include? current_start_marker text.sub! /#{Regexp.escape current_start_marker}.*#{Regexp.escape current_end_marker}/, string_with_markers elsif after_line text.sub! /(#{Regexp.escape after_line}#{Regexp.escape NEWLINE})/, '\1' + string_with_markers else text << NEWLINE << string_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 |