Search code examples
ruby-on-railsrubyrakerake-task

rake namespace vs. ruby module


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?


Solution

  • 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