Method: Thor::Actions#gsub_file

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

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

Run a regular expression replacement on a file.

Parameters

path<String>

path of the file to be changed

flag<Regexp|String>

the regexp or string to be replaced

replacement<String>

the replacement, can be also given as a block

config<Hash>

give :verbose => false to not log the status, and :force => true, to force the replacement regardless of runner behavior.

Example

gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1'

gsub_file 'README', /rake/, :green do |match|
  match << " no more. Use thor!"
end


262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/thor/actions/file_manipulation.rb', line 262

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

  return unless behavior == :invoke || config.fetch(:force, false)

  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)
    content.gsub!(flag, *args, &block)
    File.open(path, "wb") { |file| file.write(content) }
  end
end