Module: FileMutate::Mutate::ClassMethods
- Defined in:
- lib/file_mutate/mutate.rb
Instance Method Summary collapse
- #get_file(file_name) ⇒ Object
- #get_filepath(file) ⇒ Object
- #mutate_file(file, marker, place, &block) ⇒ Object
- #replace_in_file(file, regexp, *args, &block) ⇒ Object
Instance Method Details
#get_file(file_name) ⇒ Object
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/file_mutate/mutate.rb', line 32 def get_file file_name case file_name when PathString, String File.new file_name when File file_name else raise ArgumentError, "Could not be converted to a File object: #{file_name}" end end |
#get_filepath(file) ⇒ Object
43 44 45 46 47 48 49 50 51 52 |
# File 'lib/file_mutate/mutate.rb', line 43 def get_filepath file case file when PathString, String file when File file.path else raise ArgumentError, "Could not be converted to a file path: #{file_name}" end end |
#mutate_file(file, marker, place, &block) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/file_mutate/mutate.rb', line 4 def mutate_file file, marker, place, &block raise ArgumentError, "You must define a replacement marker for a :before, :before_last or :after key" if !marker file = File.get_file(file) if place == :before_last content = file.read content = content.insert_before_last yield, marker file.overwrite content return end marker_found = file.has_content? marker return nil if !marker_found replace_in_file file, /(#{marker})/mi do |match| place == :after ? "#{match}\n #{yield}" : "#{yield}\n #{match}" end true end |
#replace_in_file(file, regexp, *args, &block) ⇒ Object
25 26 27 28 29 |
# File 'lib/file_mutate/mutate.rb', line 25 def replace_in_file(file, regexp, *args, &block) file = File.get_file(file) content = file.read.gsub(regexp, *args, &block) file.overwrite content end |