rubyrakerake-task

How to reference a function in a different rake file


I want to call a function that is in another rake file.

Rake File 1:

task :build => [:some_other_tasks] do
  foo
end

def foo(type = :debug)
  # ...
end

Rake File 2:

require_relative 'path_to_rake_file_1' 

task :foo2 => [:some_other_tasks] do
      foo
    end
    

I am currently getting a no such file to load error despite confirming the path is absolutely correct.


Solution

  • Instead of defining methods inside rake files and sharing them among rake tasks, it is best practice to create a RakeHelper module and include it in your rake file. So, you could have something like:

    rake_helper.rb

    module RakeHelper
      def self.foo
      end
    end
    

    task1.rake

    include RakeHelper
    
    task :build => [:some_other_tasks] do
      RakeHelper.foo
    end
    

    task2.rake

    include RakeHelper
    
    task :foo2 => [:some_other_tasks] do
      RakeHelper.foo
    end