Last active
August 16, 2022 07:27
-
-
Save seancdavis/8cdf96c8590f49f8a1dd to your computer and use it in GitHub Desktop.
Automatically load rake tasks within namespaces based on directory structure within `lib/tasks` directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/tasks/load_tasks.rake | |
# ------------ | |
# Looks at every .rb file in the lib/tasks and adds them to rake within the | |
# namespace of their subdirectories | |
# ------------ | |
# Important to note we are looking specifically for .rb files, so they | |
# aren't added to the global rake namespace | |
Dir.glob("#{Rails.root}/lib/tasks/**/*.rb").each do |file| | |
path = file.split('/') | |
namespaces = path[(path.index('tasks') + 1)..-2] | |
filename = path.last | |
if namespaces.size > 0 | |
namespace namespaces[0].to_sym do | |
if namespaces.size > 1 | |
while namespaces.size > 1 | |
namespaces = namespaces[1..-1] | |
namespace namespaces[0].to_sym do | |
load file if namespaces.size > 0 | |
end | |
end | |
else | |
load file | |
end | |
end | |
else | |
load file | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/tasks/dir_1/dir_2/create_files.rb | |
# ------------ | |
# Tasks here are loaded into the dir_1:dir_2 namespace because it is inside | |
# the dir_1/dir_2 subdirectory | |
# ------------ | |
desc "My exampled namespaced task" | |
task :xtask => :environment do | |
# task can be executed with `bundle exec rake dir_1:dir_2:xtask` | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment