Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 920
thorstenhirsch Avatar asked Feb 08 '23 15:02

thorstenhirsch


1 Answers

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
like image 198
BroiSatse Avatar answered Feb 24 '23 17:02

BroiSatse