How to load rake task from a custom file or directory

If you are wondering how you can load a rake task from a custom file, then this is guide will help you to accomplish your task.

Lets assume you have a rake task named hello.rake under your project directory's lib folder like:

<project>/lib/tasks/hello.rake

Then you can create a simple Makefile in your directory to load it like this:

Dir.glob('lib/tasks/*.rake').each { |r| load r}

Of course, this will load all files ending with the rake extension. You can simply load hello.rake like this:

load './lib/tasks/hello.rake'

To see all the tasks that have been loaded use

rake -T

Note that we've used lib/tasks since that's the standard approach taken by Rails applications. You could use assets or whatever you prefer, though I prefer lib/tasks even in non-Rails projects.

Alternatively, you can either put your tasks into rakelib/ folder which rake loads by default or add a specific folder in your Rakefile via:

Rake.add_rakelib 'lib/tasks'