Module: Thor::Actions

Defined in:
lib/thor/actions/file_manipulation.rb

Instance Method Summary collapse

Instance Method Details

#gsub_file(path, flag, *args, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/thor/actions/file_manipulation.rb', line 7

def gsub_file(path, flag, *args, &block)
  return unless behavior == :invoke
  config = args.last.is_a?(Hash) ? args.pop : {}

  path = File.expand_path(path, destination_root)
  say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true)

  unless options[:pretend]
    content = File.binread(path)
    if block
      if block.arity == 1
        content.gsub!(flag, *args) { block.call($&) }
      else
        content.gsub!(flag, *args) { block.call(*$~) }
      end
    else
      content.gsub!(flag, *args)
    end
    File.open(path, 'wb') { |file| file.write(content) }
  end
end