How can I have helper functions with the same name in different rake tasks? The following code does not work:
# bar.rake
namespace :bar do
  desc 'bar'
  task :bar => :environment do
    bar
  end
  def bar
    puts "bar bar"
  end
end
# foo.rake
namespace :foo do
  desc 'bar'
  task :bar => :environment do
    bar
  end
  def bar
    puts "foo bar"
  end
end
The (wrong) result is:
$ rake bar:bar
foo bar
That's because rake's namespace does not work like ruby's module, so the bar function in the 2nd task redefines the bar function of the 1st task.
So what's a good solution to have local helper functions in rake tasks?
You can wrap the whole definition within a module, but you need to extend it with Rake DSL:
# bar.rake
Module.new do
  extend Rake::DSL
  namespace :bar do
    desc 'bar'
    task :bar => :environment do
      bar
    end
    def self.bar
      puts "bar bar"
    end
  end
# foo.rake
Module.new do
  extend Rake::DSL
  namespace :foo do
    desc 'bar'
    task :bar => :environment do
      bar
    end
    def self.bar
      puts "foo bar"
    end
  end
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With