Ben Downey
Ben Downey

Reputation: 2665

Rake Task Misfire

I've got a rake file that performs a find and replace operation on certain text files. When I type this at the terminal:

rake rename:changename[Funk]

I'd like the rake file to change every instance of the term Framework to Funk. The problem is that the code currently changes Framework to new_name instead.

Any ideas on what I'm doing wrong?

namespace :rename do    
  desc 'changes the name of the app'
  task :changename, :new_name do
    file_names = ['config/environments/test.rb', 'config/environments/production.rb', 'config/environment.rb']
    file_names.each do |file_name|
      text = File.read(file_name)
      File.open(file_name, "w") { |file| file << text.gsub("Framework", :new_name.to_s) }
    end   
  end 
end

Upvotes: 0

Views: 67

Answers (1)

Matheus Moreira
Matheus Moreira

Reputation: 17020

The problem is that you are effectively passing "new_name" to gsub every time. This is because :new_name.to_s simply returns the string representation of the :new_name symbol.

You already allow the user to pass arguments to your task:

task :change_name, :new_name
  # ...
end

However, you are not actually receiving the argument array, which is yielded to the block given to the task method as the second formal parameter:

task :change_name, :new_name do |task, args|
  args.with_defaults new_name: 'Funk'
  # ...
end

With the arguments in hand, all you need to do is retrieve the new name:

file << text.gsub 'Framework', args[:new_name]

Upvotes: 3

Related Questions